vibelet 1.0.6 → 1.0.7

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.cjs CHANGED
@@ -1,29 +1,28 @@
1
- "use strict";var kg=Object.create;var al=Object.defineProperty;var Pg=Object.getOwnPropertyDescriptor;var Mg=Object.getOwnPropertyNames;var Lg=Object.getPrototypeOf,Ng=Object.prototype.hasOwnProperty;var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Og=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Mg(e))!Ng.call(t,s)&&s!==n&&al(t,s,{get:()=>e[s],enumerable:!(r=Pg(e,s))||r.enumerable});return t};var St=(t,e,n)=>(n=t!=null?kg(Lg(t)):{},Og(e||!t||!t.__esModule?al(n,"default",{value:t,enumerable:!0}):n,t));var ze=v((AE,ul)=>{"use strict";var ll=["nodebuffer","arraybuffer","fragments"],cl=typeof Blob<"u";cl&&ll.push("blob");ul.exports={BINARY_TYPES:ll,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:cl,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var xn=v((EE,Cr)=>{"use strict";var{EMPTY_BUFFER:Dg}=ze(),si=Buffer[Symbol.species];function Hg(t,e){if(t.length===0)return Dg;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new si(n.buffer,n.byteOffset,r):n}function dl(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function fl(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Bg(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ii(t){if(ii.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new si(t):ArrayBuffer.isView(t)?e=new si(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ii.readOnly=!1),e}Cr.exports={concat:Hg,mask:dl,toArrayBuffer:Bg,toBuffer:ii,unmask:fl};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Cr.exports.mask=function(e,n,r,s,i){i<48?dl(e,n,r,s,i):t.mask(e,n,r,s,i)},Cr.exports.unmask=function(e,n){e.length<32?fl(e,n):t.unmask(e,n)}}catch{}});var gl=v((IE,pl)=>{"use strict";var hl=Symbol("kDone"),oi=Symbol("kRun"),ai=class{constructor(e){this[hl]=()=>{this.pending--,this[oi]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[oi]()}[oi](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[hl])}}};pl.exports=ai});var Tn=v((xE,Sl)=>{"use strict";var Cn=require("zlib"),ml=xn(),Fg=gl(),{kStatusCode:yl}=ze(),Ug=Buffer[Symbol.species],qg=Buffer.from([0,0,255,255]),Rr=Symbol("permessage-deflate"),Ye=Symbol("total-length"),$t=Symbol("callback"),st=Symbol("buffers"),Wt=Symbol("error"),Tr,li=class{constructor(e,n,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!Tr){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Tr=new Fg(s)}}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[$t];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){Tr.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Tr.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Cn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Cn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Rr]=this,this._inflate[Ye]=0,this._inflate[st]=[],this._inflate.on("error",Wg),this._inflate.on("data",_l)}this._inflate[$t]=r,this._inflate.write(e),n&&this._inflate.write(qg),this._inflate.flush(()=>{let i=this._inflate[Wt];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=ml.concat(this._inflate[st],this._inflate[Ye]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ye]=0,this._inflate[st]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Cn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Cn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Ye]=0,this._deflate[st]=[],this._deflate.on("data",$g)}this._deflate[$t]=r,this._deflate.write(e),this._deflate.flush(Cn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=ml.concat(this._deflate[st],this._deflate[Ye]);n&&(i=new Ug(i.buffer,i.byteOffset,i.length-4)),this._deflate[$t]=null,this._deflate[Ye]=0,this._deflate[st]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Sl.exports=li;function $g(t){this[st].push(t),this[Ye]+=t.length}function _l(t){if(this[Ye]+=t.length,this[Rr]._maxPayload<1||this[Ye]<=this[Rr]._maxPayload){this[st].push(t);return}this[Wt]=new RangeError("Max payload size exceeded"),this[Wt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Wt][yl]=1009,this.removeListener("data",_l),this.reset()}function Wg(t){if(this[Rr]._inflate=null,this[Wt]){this[$t](this[Wt]);return}t[yl]=1007,this[$t](t)}});var Gt=v((CE,kr)=>{"use strict";var{isUtf8:vl}=require("buffer"),{hasBlob:Gg}=ze(),jg=[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 Vg(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function ci(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function zg(t){return Gg&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}kr.exports={isBlob:zg,isValidStatusCode:Vg,isValidUTF8:ci,tokenChars:jg};if(vl)kr.exports.isValidUTF8=function(t){return t.length<24?ci(t):vl(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");kr.exports.isValidUTF8=function(e){return e.length<32?ci(e):t(e)}}catch{}});var pi=v((TE,Cl)=>{"use strict";var{Writable:Yg}=require("stream"),wl=Tn(),{BINARY_TYPES:Kg,EMPTY_BUFFER:bl,kStatusCode:Jg,kWebSocket:Qg}=ze(),{concat:ui,toArrayBuffer:Xg,unmask:Zg}=xn(),{isValidStatusCode:em,isValidUTF8:Al}=Gt(),Pr=Buffer[Symbol.species],xe=0,El=1,Il=2,xl=3,di=4,fi=5,Mr=6,hi=class extends Yg{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Kg[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Qg]=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,n,r){if(this._opcode===8&&this._state==xe)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Pr(r.buffer,r.byteOffset+e,r.length-e),new Pr(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Pr(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case xe:this.getInfo(e);break;case El:this.getPayloadLength16(e);break;case Il:this.getPayloadLength64(e);break;case xl:this.getMask();break;case di:this.getData(e);break;case fi:case Mr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[wl.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=El:this._payloadLength===127?this._state=Il: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 n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.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 n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=xl:this._state=di}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=di}getData(e){let n=bl;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Zg(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=fi,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[wl.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===xe&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=xe;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=ui(r,n):this._binaryType==="arraybuffer"?s=Xg(ui(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=xe):(this._state=Mr,setImmediate(()=>{this.emit("message",s,!0),this._state=xe,this.startLoop(e)}))}else{let s=ui(r,n);if(!this._skipUTF8Validation&&!Al(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===fi||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=xe):(this._state=Mr,setImmediate(()=>{this.emit("message",s,!1),this._state=xe,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,bl),this.end();else{let r=e.readUInt16BE(0);if(!em(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Pr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Al(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=xe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=xe):(this._state=Mr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=xe,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[Jg]=s,o}};Cl.exports=hi});var yi=v((kE,kl)=>{"use strict";var{Duplex:RE}=require("stream"),{randomFillSync:tm}=require("crypto"),Tl=Tn(),{EMPTY_BUFFER:nm,kWebSocket:rm,NOOP:sm}=ze(),{isBlob:jt,isValidStatusCode:im}=Gt(),{mask:Rl,toBuffer:vt}=xn(),Ce=Symbol("kByteLength"),om=Buffer.alloc(4),Lr=8*1024,wt,Vt=Lr,Le=0,am=1,lm=2,gi=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Le,this.onerror=sm,this[rm]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||om,n.generateMask?n.generateMask(r):(Vt===Lr&&(wt===void 0&&(wt=Buffer.alloc(Lr)),tm(wt,0,Lr),Vt=0),r[0]=wt[Vt++],r[1]=wt[Vt++],r[2]=wt[Vt++],r[3]=wt[Vt++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[Ce]!==void 0?a=n[Ce]:(e=Buffer.from(e),a=e.length):(a=e.length,s=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(Rl(e,r,c,i,a),[c]):(Rl(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=nm;else{if(typeof e!="number"||!im(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let o={[Ce]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Le?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):jt(e)?(s=e.size,i=!1):(e=vt(e),s=e.length,i=vt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ce]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};jt(e)?this._state!==Le?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Le?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):jt(e)?(s=e.size,i=!1):(e=vt(e),s=e.length,i=vt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ce]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};jt(e)?this._state!==Le?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Le?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Tl.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):jt(e)?(a=e.size,l=!1):(e=vt(e),a=e.length,l=vt.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[Ce]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};jt(e)?this._state!==Le?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==Le?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[Ce],this._state=lm,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(mi,this,a,s);return}this._bufferedBytes-=r[Ce];let o=vt(i);n?this.dispatch(o,n,r,s):(this._state=Le,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(cm,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Tl.extensionName];this._bufferedBytes+=r[Ce],this._state=am,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");mi(this,l,s);return}this._bufferedBytes-=r[Ce],this._state=Le,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===Le&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ce],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ce],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};kl.exports=gi;function mi(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function cm(t,e,n){mi(t,e,n),t.onerror(e)}});var Fl=v((PE,Bl)=>{"use strict";var{kForOnEventAttribute:Rn,kListener:_i}=ze(),Pl=Symbol("kCode"),Ml=Symbol("kData"),Ll=Symbol("kError"),Nl=Symbol("kMessage"),Ol=Symbol("kReason"),zt=Symbol("kTarget"),Dl=Symbol("kType"),Hl=Symbol("kWasClean"),Ke=class{constructor(e){this[zt]=null,this[Dl]=e}get target(){return this[zt]}get type(){return this[Dl]}};Object.defineProperty(Ke.prototype,"target",{enumerable:!0});Object.defineProperty(Ke.prototype,"type",{enumerable:!0});var bt=class extends Ke{constructor(e,n={}){super(e),this[Pl]=n.code===void 0?0:n.code,this[Ol]=n.reason===void 0?"":n.reason,this[Hl]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Pl]}get reason(){return this[Ol]}get wasClean(){return this[Hl]}};Object.defineProperty(bt.prototype,"code",{enumerable:!0});Object.defineProperty(bt.prototype,"reason",{enumerable:!0});Object.defineProperty(bt.prototype,"wasClean",{enumerable:!0});var Yt=class extends Ke{constructor(e,n={}){super(e),this[Ll]=n.error===void 0?null:n.error,this[Nl]=n.message===void 0?"":n.message}get error(){return this[Ll]}get message(){return this[Nl]}};Object.defineProperty(Yt.prototype,"error",{enumerable:!0});Object.defineProperty(Yt.prototype,"message",{enumerable:!0});var kn=class extends Ke{constructor(e,n={}){super(e),this[Ml]=n.data===void 0?null:n.data}get data(){return this[Ml]}};Object.defineProperty(kn.prototype,"data",{enumerable:!0});var um={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Rn]&&s[_i]===e&&!s[Rn])return;let r;if(t==="message")r=function(i,o){let a=new kn("message",{data:o?i:i.toString()});a[zt]=this,Nr(e,this,a)};else if(t==="close")r=function(i,o){let a=new bt("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[zt]=this,Nr(e,this,a)};else if(t==="error")r=function(i){let o=new Yt("error",{error:i,message:i.message});o[zt]=this,Nr(e,this,o)};else if(t==="open")r=function(){let i=new Ke("open");i[zt]=this,Nr(e,this,i)};else return;r[Rn]=!!n[Rn],r[_i]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[_i]===e&&!n[Rn]){this.removeListener(t,n);break}}};Bl.exports={CloseEvent:bt,ErrorEvent:Yt,Event:Ke,EventTarget:um,MessageEvent:kn};function Nr(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Si=v((ME,Ul)=>{"use strict";var{tokenChars:Pn}=Gt();function $e(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function dm(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,a,l=-1,c=-1,u=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),o===void 0)if(u===-1&&Pn[c]===1)l===-1&&(l=d);else if(d!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(l,u);c===44?($e(e,p,n),n=Object.create(null)):o=p,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&Pn[c]===1)l===-1&&(l=d);else if(c===32||c===9)u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),$e(n,t.slice(l,u),!0),c===44&&($e(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,d),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(s){if(Pn[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(Pn[c]===1)l===-1&&(l=d);else if(c===34&&l!==-1)i=!1,u=d;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&Pn[c]===1)l===-1&&(l=d);else if(l!==-1&&(c===32||c===9))u===-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=t.slice(l,u);r&&(p=p.replace(/\\/g,""),r=!1),$e(n,a,p),c===44&&($e(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(l,u);return o===void 0?$e(e,f,n):(a===void 0?$e(n,f,!0):r?$e(n,a,f.replace(/\\/g,"")):$e(n,a,f),$e(e,o,n)),e}function fm(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ul.exports={format:fm,parse:dm}});var Br=v((OE,Xl)=>{"use strict";var hm=require("events"),pm=require("https"),gm=require("http"),Wl=require("net"),mm=require("tls"),{randomBytes:ym,createHash:_m}=require("crypto"),{Duplex:LE,Readable:NE}=require("stream"),{URL:vi}=require("url"),it=Tn(),Sm=pi(),vm=yi(),{isBlob:wm}=Gt(),{BINARY_TYPES:ql,CLOSE_TIMEOUT:bm,EMPTY_BUFFER:Or,GUID:Am,kForOnEventAttribute:wi,kListener:Em,kStatusCode:Im,kWebSocket:ae,NOOP:Gl}=ze(),{EventTarget:{addEventListener:xm,removeEventListener:Cm}}=Fl(),{format:Tm,parse:Rm}=Si(),{toBuffer:km}=xn(),jl=Symbol("kAborted"),bi=[8,13],Je=["CONNECTING","OPEN","CLOSING","CLOSED"],Pm=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,V=class t extends hm{constructor(e,n,r){super(),this._binaryType=ql[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Or,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,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Vl(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ql.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,n,r){let s=new Sm({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new vm(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[ae]=this,i[ae]=this,e[ae]=this,s.on("conclude",Nm),s.on("drain",Om),s.on("error",Dm),s.on("message",Hm),s.on("ping",Bm),s.on("pong",Fm),i.onerror=Um,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Kl),e.on("data",Hr),e.on("end",Jl),e.on("error",Ql),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[it.extensionName]&&this._extensions[it.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){be(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,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Yl(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ai(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Or,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ai(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Or,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ai(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[it.extensionName]||(s.compress=!1),this._sender.send(e||Or,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){be(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(V,"CONNECTING",{enumerable:!0,value:Je.indexOf("CONNECTING")});Object.defineProperty(V.prototype,"CONNECTING",{enumerable:!0,value:Je.indexOf("CONNECTING")});Object.defineProperty(V,"OPEN",{enumerable:!0,value:Je.indexOf("OPEN")});Object.defineProperty(V.prototype,"OPEN",{enumerable:!0,value:Je.indexOf("OPEN")});Object.defineProperty(V,"CLOSING",{enumerable:!0,value:Je.indexOf("CLOSING")});Object.defineProperty(V.prototype,"CLOSING",{enumerable:!0,value:Je.indexOf("CLOSING")});Object.defineProperty(V,"CLOSED",{enumerable:!0,value:Je.indexOf("CLOSED")});Object.defineProperty(V.prototype,"CLOSED",{enumerable:!0,value:Je.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(V.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(V.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[wi])return e[Em];return null},set(e){for(let n of this.listeners(t))if(n[wi]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[wi]:!0})}})});V.prototype.addEventListener=xm;V.prototype.removeEventListener=Cm;Xl.exports=V;function Vl(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:bm,protocolVersion:bi[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,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=s.autoPong,t._closeTimeout=s.closeTimeout,!bi.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${bi.join(", ")})`);let i;if(e instanceof vi)i=e;else try{i=new vi(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let h=new SyntaxError(l);if(t._redirects===0)throw h;Dr(t,h);return}let c=o?443:80,u=ym(16).toString("base64"),d=o?pm.request:gm.request,f=new Set,p;if(s.createConnection=s.createConnection||(o?Lm:Mm),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(p=new it(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Tm({[it.extensionName]:p.offer()})),n.length){for(let h of n){if(typeof h!="string"||!Pm.test(h)||f.has(h))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(h)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let h=s.path.split(":");s.socketPath=h[0],s.path=h[1]}let g;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let h=r&&r.headers;if(r={...r,headers:{}},h)for(let[_,w]of Object.entries(h))r.headers[_.toLowerCase()]=w}else if(t.listenerCount("redirect")===0){let h=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!h||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,h||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),g=t._req=d(s),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(s);s.timeout&&g.on("timeout",()=>{be(t,g,"Opening handshake has timed out")}),g.on("error",h=>{g===null||g[jl]||(g=t._req=null,Dr(t,h))}),g.on("response",h=>{let _=h.headers.location,w=h.statusCode;if(_&&s.followRedirects&&w>=300&&w<400){if(++t._redirects>s.maxRedirects){be(t,g,"Maximum redirects exceeded");return}g.abort();let E;try{E=new vi(_,e)}catch{let N=new SyntaxError(`Invalid URL: ${_}`);Dr(t,N);return}Vl(t,E,n,r)}else t.emit("unexpected-response",g,h)||be(t,g,`Unexpected server response: ${h.statusCode}`)}),g.on("upgrade",(h,_,w)=>{if(t.emit("upgrade",h),t.readyState!==V.CONNECTING)return;g=t._req=null;let E=h.headers.upgrade;if(E===void 0||E.toLowerCase()!=="websocket"){be(t,_,"Invalid Upgrade header");return}let L=_m("sha1").update(u+Am).digest("base64");if(h.headers["sec-websocket-accept"]!==L){be(t,_,"Invalid Sec-WebSocket-Accept header");return}let N=h.headers["sec-websocket-protocol"],O;if(N!==void 0?f.size?f.has(N)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":f.size&&(O="Server sent no subprotocol"),O){be(t,_,O);return}N&&(t._protocol=N);let X=h.headers["sec-websocket-extensions"];if(X!==void 0){if(!p){be(t,_,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=Rm(X)}catch{be(t,_,"Invalid Sec-WebSocket-Extensions header");return}let x=Object.keys(U);if(x.length!==1||x[0]!==it.extensionName){be(t,_,"Server indicated an extension that was not requested");return}try{p.accept(U[it.extensionName])}catch{be(t,_,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[it.extensionName]=p}t.setSocket(_,w,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(g,t):g.end()}function Dr(t,e){t._readyState=V.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Mm(t){return t.path=t.socketPath,Wl.connect(t)}function Lm(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Wl.isIP(t.host)?"":t.host),mm.connect(t)}function be(t,e,n){t._readyState=V.CLOSING;let r=new Error(n);Error.captureStackTrace(r,be),e.setHeader?(e[jl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Dr,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ai(t,e,n){if(e){let r=wm(e)?e.size:km(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Je[t.readyState]})`);process.nextTick(n,r)}}function Nm(t,e){let n=this[ae];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[ae]!==void 0&&(n._socket.removeListener("data",Hr),process.nextTick(zl,n._socket),t===1005?n.close():n.close(t,e))}function Om(){let t=this[ae];t.isPaused||t._socket.resume()}function Dm(t){let e=this[ae];e._socket[ae]!==void 0&&(e._socket.removeListener("data",Hr),process.nextTick(zl,e._socket),e.close(t[Im])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function $l(){this[ae].emitClose()}function Hm(t,e){this[ae].emit("message",t,e)}function Bm(t){let e=this[ae];e._autoPong&&e.pong(t,!this._isServer,Gl),e.emit("ping",t)}function Fm(t){this[ae].emit("pong",t)}function zl(t){t.resume()}function Um(t){let e=this[ae];e.readyState!==V.CLOSED&&(e.readyState===V.OPEN&&(e._readyState=V.CLOSING,Yl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Yl(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Kl(){let t=this[ae];if(this.removeListener("close",Kl),this.removeListener("data",Hr),this.removeListener("end",Jl),t._readyState=V.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[ae]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",$l),t._receiver.on("finish",$l))}function Hr(t){this[ae]._receiver.write(t)||this.pause()}function Jl(){let t=this[ae];t._readyState=V.CLOSING,t._receiver.end(),this.end()}function Ql(){let t=this[ae];this.removeListener("error",Ql),this.on("error",Gl),t&&(t._readyState=V.CLOSING,this.destroy())}});var nc=v((HE,tc)=>{"use strict";var DE=Br(),{Duplex:qm}=require("stream");function Zl(t){t.emit("close")}function $m(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ec(t){this.removeListener("error",ec),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Wm(t,e){let n=!0,r=new qm({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(Zl,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(Zl,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",$m),r.on("error",ec),r}tc.exports=Wm});var sc=v((BE,rc)=>{"use strict";var{tokenChars:Gm}=Gt();function jm(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&Gm[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}rc.exports={parse:jm}});var dc=v((UE,uc)=>{"use strict";var Vm=require("events"),Fr=require("http"),{Duplex:FE}=require("stream"),{createHash:zm}=require("crypto"),ic=Si(),At=Tn(),Ym=sc(),Km=Br(),{CLOSE_TIMEOUT:Jm,GUID:Qm,kWebSocket:Xm}=ze(),Zm=/^[+/0-9A-Za-z]{22}==$/,oc=0,ac=1,cc=2,Ei=class extends Vm{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Jm,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Km,...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=Fr.createServer((r,s)=>{let i=Fr.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=ey(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=oc}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===cc){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Mn,this);return}if(e&&this.once("close",e),this._state!==ac)if(this._state=ac,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(Mn,this):process.nextTick(Mn,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Mn(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",lc);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Et(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Et(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Zm.test(i)){Et(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Et(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ln(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Ym.parse(l)}catch{Et(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let f=new At(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=ic.parse(u);p[At.extensionName]&&(f.accept(p[At.extensionName]),d[At.extensionName]=f)}catch{Et(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(p,g,h,_)=>{if(!p)return Ln(n,g||401,h,_);this.completeUpgrade(d,i,c,e,n,r,s)});return}if(!this.options.verifyClient(f))return Ln(n,401)}this.completeUpgrade(d,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Xm])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>oc)return Ln(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${zm("sha1").update(n+Qm).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[At.extensionName]){let d=e[At.extensionName].params,f=ic.format({[At.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
1
+ "use strict";var dd=Object.create;var Ui=Object.defineProperty;var fd=Object.getOwnPropertyDescriptor;var pd=Object.getOwnPropertyNames;var hd=Object.getPrototypeOf,gd=Object.prototype.hasOwnProperty;var y=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var md=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of pd(e))!gd.call(t,s)&&s!==n&&Ui(t,s,{get:()=>e[s],enumerable:!(r=fd(e,s))||r.enumerable});return t};var rt=(t,e,n)=>(n=t!=null?dd(hd(t)):{},md(e||!t||!t.__esModule?Ui(n,"default",{value:t,enumerable:!0}):n,t));var ge=y((Jy,Gi)=>{"use strict";var qi=["nodebuffer","arraybuffer","fragments"],Wi=typeof Blob<"u";Wi&&qi.push("blob");Gi.exports={BINARY_TYPES:qi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Wi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Bt=y((Ky,Tn)=>{"use strict";var{EMPTY_BUFFER:yd}=ge(),Or=Buffer[Symbol.species];function vd(t,e){if(t.length===0)return yd;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let s=0;s<t.length;s++){let i=t[s];n.set(i,r),r+=i.length}return r<e?new Or(n.buffer,n.byteOffset,r):n}function ji(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Vi(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Sd(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Br(t){if(Br.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Or(t):ArrayBuffer.isView(t)?e=new Or(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Br.readOnly=!1),e}Tn.exports={concat:vd,mask:ji,toArrayBuffer:Sd,toBuffer:Br,unmask:Vi};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Tn.exports.mask=function(e,n,r,s,i){i<48?ji(e,n,r,s,i):t.mask(e,n,r,s,i)},Tn.exports.unmask=function(e,n){e.length<32?Vi(e,n):t.unmask(e,n)}}catch{}});var Yi=y((Qy,zi)=>{"use strict";var $i=Symbol("kDone"),Dr=Symbol("kRun"),Hr=class{constructor(e){this[$i]=()=>{this.pending--,this[Dr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Dr]()}[Dr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[$i])}}};zi.exports=Hr});var Ht=y((Xy,Xi)=>{"use strict";var Dt=require("zlib"),Ji=Bt(),_d=Yi(),{kStatusCode:Ki}=ge(),bd=Buffer[Symbol.species],wd=Buffer.from([0,0,255,255]),Cn=Symbol("permessage-deflate"),me=Symbol("total-length"),st=Symbol("callback"),Ie=Symbol("buffers"),it=Symbol("error"),xn,Fr=class{constructor(e,n,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!n,this._deflate=null,this._inflate=null,this.params=null,!xn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;xn=new _d(s)}}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[st];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(s=>!(n.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>s.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let s=n[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=s})}),e}decompress(e,n,r){xn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){xn.add(s=>{this._compress(e,n,(i,o)=>{s(),r(i,o)})})}_decompress(e,n,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Dt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Dt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Cn]=this,this._inflate[me]=0,this._inflate[Ie]=[],this._inflate.on("error",Ad),this._inflate.on("data",Qi)}this._inflate[st]=r,this._inflate.write(e),n&&this._inflate.write(wd),this._inflate.flush(()=>{let i=this._inflate[it];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Ji.concat(this._inflate[Ie],this._inflate[me]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[me]=0,this._inflate[Ie]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Dt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Dt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[me]=0,this._deflate[Ie]=[],this._deflate.on("data",Id)}this._deflate[st]=r,this._deflate.write(e),this._deflate.flush(Dt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Ji.concat(this._deflate[Ie],this._deflate[me]);n&&(i=new bd(i.buffer,i.byteOffset,i.length-4)),this._deflate[st]=null,this._deflate[me]=0,this._deflate[Ie]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Xi.exports=Fr;function Id(t){this[Ie].push(t),this[me]+=t.length}function Qi(t){if(this[me]+=t.length,this[Cn]._maxPayload<1||this[me]<=this[Cn]._maxPayload){this[Ie].push(t);return}this[it]=new RangeError("Max payload size exceeded"),this[it].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[it][Ki]=1009,this.removeListener("data",Qi),this.reset()}function Ad(t){if(this[Cn]._inflate=null,this[it]){this[st](this[it]);return}t[Ki]=1007,this[st](t)}});var ot=y((Zy,kn)=>{"use strict";var{isUtf8:Zi}=require("buffer"),{hasBlob:Td}=ge(),xd=[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 Cd(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ur(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function kd(t){return Td&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}kn.exports={isBlob:kd,isValidStatusCode:Cd,isValidUTF8:Ur,tokenChars:xd};if(Zi)kn.exports.isValidUTF8=function(t){return t.length<24?Ur(t):Zi(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");kn.exports.isValidUTF8=function(e){return e.length<32?Ur(e):t(e)}}catch{}});var Vr=y((ev,oo)=>{"use strict";var{Writable:Ed}=require("stream"),eo=Ht(),{BINARY_TYPES:Pd,EMPTY_BUFFER:to,kStatusCode:Rd,kWebSocket:Md}=ge(),{concat:qr,toArrayBuffer:Ld,unmask:Nd}=Bt(),{isValidStatusCode:Od,isValidUTF8:no}=ot(),En=Buffer[Symbol.species],X=0,ro=1,so=2,io=3,Wr=4,Gr=5,Pn=6,jr=class extends Ed{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Pd[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Md]=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=X}_write(e,n,r){if(this._opcode===8&&this._state==X)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new En(r.buffer,r.byteOffset+e,r.length-e),new En(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=n.length-e;e>=r.length?n.set(this._buffers.shift(),s):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new En(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case X:this.getInfo(e);break;case ro:this.getPayloadLength16(e);break;case so:this.getPayloadLength64(e);break;case io:this.getMask();break;case Wr:this.getData(e);break;case Gr:case Pn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(n[0]&64)===64;if(r&&!this._extensions[eo.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=ro:this._payloadLength===127?this._state=so: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 n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+n.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 n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=io:this._state=Wr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Wr}getData(e){let n=to;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Nd(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Gr,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[eo.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===X&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=X;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=qr(r,n):this._binaryType==="arraybuffer"?s=Ld(qr(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=X):(this._state=Pn,setImmediate(()=>{this.emit("message",s,!0),this._state=X,this.startLoop(e)}))}else{let s=qr(r,n);if(!this._skipUTF8Validation&&!no(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Gr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=X):(this._state=Pn,setImmediate(()=>{this.emit("message",s,!1),this._state=X,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,to),this.end();else{let r=e.readUInt16BE(0);if(!Od(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new En(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!no(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=X;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=X):(this._state=Pn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=X,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[Rd]=s,o}};oo.exports=jr});var Yr=y((nv,co)=>{"use strict";var{Duplex:tv}=require("stream"),{randomFillSync:Bd}=require("crypto"),ao=Ht(),{EMPTY_BUFFER:Dd,kWebSocket:Hd,NOOP:Fd}=ge(),{isBlob:at,isValidStatusCode:Ud}=ot(),{mask:lo,toBuffer:He}=Bt(),Z=Symbol("kByteLength"),qd=Buffer.alloc(4),Rn=8*1024,Fe,lt=Rn,se=0,Wd=1,Gd=2,$r=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=se,this.onerror=Fd,this[Hd]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||qd,n.generateMask?n.generateMask(r):(lt===Rn&&(Fe===void 0&&(Fe=Buffer.alloc(Rn)),Bd(Fe,0,Rn),lt=0),r[0]=Fe[lt++],r[1]=Fe[lt++],r[2]=Fe[lt++],r[3]=Fe[lt++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[Z]!==void 0?a=n[Z]:(e=Buffer.from(e),a=e.length):(a=e.length,s=n.mask&&n.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(s?a+i:i);return c[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),n.mask?(c[1]|=128,c[i-4]=r[0],c[i-3]=r[1],c[i-2]=r[2],c[i-1]=r[3],o?[c,e]:s?(lo(e,r,c,i,a),[c]):(lo(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=Dd;else{if(typeof e!="number"||!Ud(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof n=="string"?i.write(n,2):i.set(n,2)}}let o={[Z]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==se?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):at(e)?(s=e.size,i=!1):(e=He(e),s=e.length,i=He.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Z]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};at(e)?this._state!==se?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==se?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):at(e)?(s=e.size,i=!1):(e=He(e),s=e.length,i=He.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Z]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};at(e)?this._state!==se?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==se?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[ao.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):at(e)?(a=e.size,l=!1):(e=He(e),a=e.length,l=He.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[Z]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};at(e)?this._state!==se?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==se?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[Z],this._state=Gd,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(zr,this,a,s);return}this._bufferedBytes-=r[Z];let o=He(i);n?this.dispatch(o,n,r,s):(this._state=se,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(jd,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[ao.extensionName];this._bufferedBytes+=r[Z],this._state=Wd,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");zr(this,l,s);return}this._bufferedBytes-=r[Z],this._state=se,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===se&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Z],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Z],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};co.exports=$r;function zr(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let s=t._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function jd(t,e,n){zr(t,e,n),t.onerror(e)}});var So=y((rv,vo)=>{"use strict";var{kForOnEventAttribute:Ft,kListener:Jr}=ge(),uo=Symbol("kCode"),fo=Symbol("kData"),po=Symbol("kError"),ho=Symbol("kMessage"),go=Symbol("kReason"),ct=Symbol("kTarget"),mo=Symbol("kType"),yo=Symbol("kWasClean"),ye=class{constructor(e){this[ct]=null,this[mo]=e}get target(){return this[ct]}get type(){return this[mo]}};Object.defineProperty(ye.prototype,"target",{enumerable:!0});Object.defineProperty(ye.prototype,"type",{enumerable:!0});var Ue=class extends ye{constructor(e,n={}){super(e),this[uo]=n.code===void 0?0:n.code,this[go]=n.reason===void 0?"":n.reason,this[yo]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[uo]}get reason(){return this[go]}get wasClean(){return this[yo]}};Object.defineProperty(Ue.prototype,"code",{enumerable:!0});Object.defineProperty(Ue.prototype,"reason",{enumerable:!0});Object.defineProperty(Ue.prototype,"wasClean",{enumerable:!0});var ut=class extends ye{constructor(e,n={}){super(e),this[po]=n.error===void 0?null:n.error,this[ho]=n.message===void 0?"":n.message}get error(){return this[po]}get message(){return this[ho]}};Object.defineProperty(ut.prototype,"error",{enumerable:!0});Object.defineProperty(ut.prototype,"message",{enumerable:!0});var Ut=class extends ye{constructor(e,n={}){super(e),this[fo]=n.data===void 0?null:n.data}get data(){return this[fo]}};Object.defineProperty(Ut.prototype,"data",{enumerable:!0});var Vd={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Ft]&&s[Jr]===e&&!s[Ft])return;let r;if(t==="message")r=function(i,o){let a=new Ut("message",{data:o?i:i.toString()});a[ct]=this,Mn(e,this,a)};else if(t==="close")r=function(i,o){let a=new Ue("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[ct]=this,Mn(e,this,a)};else if(t==="error")r=function(i){let o=new ut("error",{error:i,message:i.message});o[ct]=this,Mn(e,this,o)};else if(t==="open")r=function(){let i=new ye("open");i[ct]=this,Mn(e,this,i)};else return;r[Ft]=!!n[Ft],r[Jr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Jr]===e&&!n[Ft]){this.removeListener(t,n);break}}};vo.exports={CloseEvent:Ue,ErrorEvent:ut,Event:ye,EventTarget:Vd,MessageEvent:Ut};function Mn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Kr=y((sv,_o)=>{"use strict";var{tokenChars:qt}=ot();function de(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function $d(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,a,l=-1,c=-1,u=-1,d=0;for(;d<t.length;d++)if(c=t.charCodeAt(d),o===void 0)if(u===-1&&qt[c]===1)l===-1&&(l=d);else if(d!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(l,u);c===44?(de(e,h,n),n=Object.create(null)):o=h,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&qt[c]===1)l===-1&&(l=d);else if(c===32||c===9)u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),de(n,t.slice(l,u),!0),c===44&&(de(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,d),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(s){if(qt[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(qt[c]===1)l===-1&&(l=d);else if(c===34&&l!==-1)i=!1,u=d;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&t.charCodeAt(d-1)===61)i=!0;else if(u===-1&&qt[c]===1)l===-1&&(l=d);else if(l!==-1&&(c===32||c===9))u===-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let h=t.slice(l,u);r&&(h=h.replace(/\\/g,""),r=!1),de(n,a,h),c===44&&(de(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=t.slice(l,u);return o===void 0?de(e,f,n):(a===void 0?de(n,f,!0):r?de(n,a,f.replace(/\\/g,"")):de(n,a,f),de(e,o,n)),e}function zd(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}_o.exports={format:zd,parse:$d}});var Bn=y((av,Mo)=>{"use strict";var Yd=require("events"),Jd=require("https"),Kd=require("http"),Io=require("net"),Qd=require("tls"),{randomBytes:Xd,createHash:Zd}=require("crypto"),{Duplex:iv,Readable:ov}=require("stream"),{URL:Qr}=require("url"),Ae=Ht(),ef=Vr(),tf=Yr(),{isBlob:nf}=ot(),{BINARY_TYPES:bo,CLOSE_TIMEOUT:rf,EMPTY_BUFFER:Ln,GUID:sf,kForOnEventAttribute:Xr,kListener:of,kStatusCode:af,kWebSocket:F,NOOP:Ao}=ge(),{EventTarget:{addEventListener:lf,removeEventListener:cf}}=So(),{format:uf,parse:df}=Kr(),{toBuffer:ff}=Bt(),To=Symbol("kAborted"),Zr=[8,13],ve=["CONNECTING","OPEN","CLOSING","CLOSED"],pf=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,k=class t extends Yd{constructor(e,n,r){super(),this._binaryType=bo[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ln,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,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),xo(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){bo.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,n,r){let s=new ef({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new tf(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[F]=this,i[F]=this,e[F]=this,s.on("conclude",mf),s.on("drain",yf),s.on("error",vf),s.on("message",Sf),s.on("ping",_f),s.on("pong",bf),i.onerror=wf,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Eo),e.on("data",On),e.on("end",Po),e.on("error",Ro),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[Ae.extensionName]&&this._extensions[Ae.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(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,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ko(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){es(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Ln,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){es(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Ln,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){es(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ae.extensionName]||(s.compress=!1),this._sender.send(e||Ln,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Y(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(k,"CONNECTING",{enumerable:!0,value:ve.indexOf("CONNECTING")});Object.defineProperty(k.prototype,"CONNECTING",{enumerable:!0,value:ve.indexOf("CONNECTING")});Object.defineProperty(k,"OPEN",{enumerable:!0,value:ve.indexOf("OPEN")});Object.defineProperty(k.prototype,"OPEN",{enumerable:!0,value:ve.indexOf("OPEN")});Object.defineProperty(k,"CLOSING",{enumerable:!0,value:ve.indexOf("CLOSING")});Object.defineProperty(k.prototype,"CLOSING",{enumerable:!0,value:ve.indexOf("CLOSING")});Object.defineProperty(k,"CLOSED",{enumerable:!0,value:ve.indexOf("CLOSED")});Object.defineProperty(k.prototype,"CLOSED",{enumerable:!0,value:ve.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(k.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(k.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Xr])return e[of];return null},set(e){for(let n of this.listeners(t))if(n[Xr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Xr]:!0})}})});k.prototype.addEventListener=lf;k.prototype.removeEventListener=cf;Mo.exports=k;function xo(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:rf,protocolVersion:Zr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,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=s.autoPong,t._closeTimeout=s.closeTimeout,!Zr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Zr.join(", ")})`);let i;if(e instanceof Qr)i=e;else try{i=new Qr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),t._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let p=new SyntaxError(l);if(t._redirects===0)throw p;Nn(t,p);return}let c=o?443:80,u=Xd(16).toString("base64"),d=o?Jd.request:Kd.request,f=new Set,h;if(s.createConnection=s.createConnection||(o?gf:hf),s.defaultPort=s.defaultPort||c,s.port=i.port||c,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(h=new Ae(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=uf({[Ae.extensionName]:h.offer()})),n.length){for(let p of n){if(typeof p!="string"||!pf.test(p)||f.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(p)}s.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let p=s.path.split(":");s.socketPath=p[0],s.path=p[1]}let g;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let p=r&&r.headers;if(r={...r,headers:{}},p)for(let[m,v]of Object.entries(p))r.headers[m.toLowerCase()]=v}else if(t.listenerCount("redirect")===0){let p=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!p||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,p||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),g=t._req=d(s),t._redirects&&t.emit("redirect",t.url,g)}else g=t._req=d(s);s.timeout&&g.on("timeout",()=>{Y(t,g,"Opening handshake has timed out")}),g.on("error",p=>{g===null||g[To]||(g=t._req=null,Nn(t,p))}),g.on("response",p=>{let m=p.headers.location,v=p.statusCode;if(m&&s.followRedirects&&v>=300&&v<400){if(++t._redirects>s.maxRedirects){Y(t,g,"Maximum redirects exceeded");return}g.abort();let b;try{b=new Qr(m,e)}catch{let C=new SyntaxError(`Invalid URL: ${m}`);Nn(t,C);return}xo(t,b,n,r)}else t.emit("unexpected-response",g,p)||Y(t,g,`Unexpected server response: ${p.statusCode}`)}),g.on("upgrade",(p,m,v)=>{if(t.emit("upgrade",p),t.readyState!==k.CONNECTING)return;g=t._req=null;let b=p.headers.upgrade;if(b===void 0||b.toLowerCase()!=="websocket"){Y(t,m,"Invalid Upgrade header");return}let K=Zd("sha1").update(u+sf).digest("base64");if(p.headers["sec-websocket-accept"]!==K){Y(t,m,"Invalid Sec-WebSocket-Accept header");return}let C=p.headers["sec-websocket-protocol"],H;if(C!==void 0?f.size?f.has(C)||(H="Server sent an invalid subprotocol"):H="Server sent a subprotocol but none was requested":f.size&&(H="Server sent no subprotocol"),H){Y(t,m,H);return}C&&(t._protocol=C);let Q=p.headers["sec-websocket-extensions"];if(Q!==void 0){if(!h){Y(t,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ue;try{ue=df(Q)}catch{Y(t,m,"Invalid Sec-WebSocket-Extensions header");return}let nt=Object.keys(ue);if(nt.length!==1||nt[0]!==Ae.extensionName){Y(t,m,"Server indicated an extension that was not requested");return}try{h.accept(ue[Ae.extensionName])}catch{Y(t,m,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ae.extensionName]=h}t.setSocket(m,v,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(g,t):g.end()}function Nn(t,e){t._readyState=k.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function hf(t){return t.path=t.socketPath,Io.connect(t)}function gf(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Io.isIP(t.host)?"":t.host),Qd.connect(t)}function Y(t,e,n){t._readyState=k.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Y),e.setHeader?(e[To]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Nn,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function es(t,e,n){if(e){let r=nf(e)?e.size:ff(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${ve[t.readyState]})`);process.nextTick(n,r)}}function mf(t,e){let n=this[F];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[F]!==void 0&&(n._socket.removeListener("data",On),process.nextTick(Co,n._socket),t===1005?n.close():n.close(t,e))}function yf(){let t=this[F];t.isPaused||t._socket.resume()}function vf(t){let e=this[F];e._socket[F]!==void 0&&(e._socket.removeListener("data",On),process.nextTick(Co,e._socket),e.close(t[af])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function wo(){this[F].emitClose()}function Sf(t,e){this[F].emit("message",t,e)}function _f(t){let e=this[F];e._autoPong&&e.pong(t,!this._isServer,Ao),e.emit("ping",t)}function bf(t){this[F].emit("pong",t)}function Co(t){t.resume()}function wf(t){let e=this[F];e.readyState!==k.CLOSED&&(e.readyState===k.OPEN&&(e._readyState=k.CLOSING,ko(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function ko(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Eo(){let t=this[F];if(this.removeListener("close",Eo),this.removeListener("data",On),this.removeListener("end",Po),t._readyState=k.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[F]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",wo),t._receiver.on("finish",wo))}function On(t){this[F]._receiver.write(t)||this.pause()}function Po(){let t=this[F];t._readyState=k.CLOSING,t._receiver.end(),this.end()}function Ro(){let t=this[F];this.removeListener("error",Ro),this.on("error",Ao),t&&(t._readyState=k.CLOSING,this.destroy())}});var Bo=y((cv,Oo)=>{"use strict";var lv=Bn(),{Duplex:If}=require("stream");function Lo(t){t.emit("close")}function Af(){!this.destroyed&&this._writableState.finished&&this.destroy()}function No(t){this.removeListener("error",No),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Tf(t,e){let n=!0,r=new If({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||t.pause()}),t.once("error",function(i){r.destroyed||(n=!1,r.destroy(i))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(Lo,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(Lo,r)}),n&&t.terminate()},r._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(s,i,o)});return}t.send(s,o)},r.on("end",Af),r.on("error",No),r}Oo.exports=Tf});var Ho=y((uv,Do)=>{"use strict";var{tokenChars:xf}=ot();function Cf(t){let e=new Set,n=-1,r=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(r===-1&&xf[o]===1)n===-1&&(n=s);else if(s!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=s);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(n,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Do.exports={parse:Cf}});var Vo=y((fv,jo)=>{"use strict";var kf=require("events"),Dn=require("http"),{Duplex:dv}=require("stream"),{createHash:Ef}=require("crypto"),Fo=Kr(),qe=Ht(),Pf=Ho(),Rf=Bn(),{CLOSE_TIMEOUT:Mf,GUID:Lf,kWebSocket:Nf}=ge(),Of=/^[+/0-9A-Za-z]{22}==$/,Uo=0,qo=1,Go=2,ts=class extends kf{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Mf,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Rf,...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=Dn.createServer((r,s)=>{let i=Dn.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Bf(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Uo}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===Go){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Wt,this);return}if(e&&this.once("close",e),this._state!==qo)if(this._state=qo,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(Wt,this):process.nextTick(Wt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Wt(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,s){n.on("error",Wo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){We(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){We(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Of.test(i)){We(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){We(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Gt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Pf.parse(l)}catch{We(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let f=new qe(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=Fo.parse(u);h[qe.extensionName]&&(f.accept(h[qe.extensionName]),d[qe.extensionName]=f)}catch{We(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(h,g,p,m)=>{if(!h)return Gt(n,g||401,p,m);this.completeUpgrade(d,i,c,e,n,r,s)});return}if(!this.options.verifyClient(f))return Gt(n,401)}this.completeUpgrade(d,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Nf])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Uo)return Gt(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ef("sha1").update(n+Lf).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[qe.extensionName]){let d=e[qe.extensionName].params,f=Fo.format({[qe.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
2
2
  `).join(`\r
3
- `)),i.removeListener("error",lc),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Mn,this)})),a(u,s)}};uc.exports=Ei;function ey(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Mn(t){t._state=cc,t.emit("close")}function lc(){this.destroy()}function Ln(t,e,n,r){n=n||Fr.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Fr.STATUS_CODES[e]}\r
3
+ `)),i.removeListener("error",Wo),u.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Wt,this)})),a(u,s)}};jo.exports=ts;function Bf(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function Wt(t){t._state=Go,t.emit("close")}function Wo(){this.destroy()}function Gt(t,e,n,r){n=n||Dn.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Dn.STATUS_CODES[e]}\r
4
4
  `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
5
5
  `)+`\r
6
6
  \r
7
- `+n)}function Et(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Et),t.emit("wsClientError",o,n,e)}else Ln(n,r,s,i)}});var xi=v(($E,fc)=>{fc.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ot=v(It=>{var Ci,iy=[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];It.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};It.getSymbolTotalCodewords=function(e){return iy[e]};It.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};It.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Ci=e};It.isKanjiModeEnabled=function(){return typeof Ci<"u"};It.toSJIS=function(e){return Ci(e)}});var Ur=v(Te=>{Te.L={bit:1};Te.M={bit:0};Te.Q={bit:3};Te.H={bit:2};function oy(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return Te.L;case"m":case"medium":return Te.M;case"q":case"quartile":return Te.Q;case"h":case"high":return Te.H;default:throw new Error("Unknown EC Level: "+t)}}Te.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};Te.from=function(e,n){if(Te.isValid(e))return e;try{return oy(e)}catch{return n}}});var gc=v((jE,pc)=>{function hc(){this.buffer=[],this.length=0}hc.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 n=0;n<e;n++)this.putBit((t>>>e-n-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++}};pc.exports=hc});var yc=v((VE,mc)=>{function Nn(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)}Nn.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};Nn.prototype.get=function(t,e){return this.data[t*this.size+e]};Nn.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};Nn.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};mc.exports=Nn});var _c=v(qr=>{var ay=ot().getSymbolSize;qr.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=ay(e),s=r===145?26:Math.ceil((r-13)/(2*n-2))*2,i=[r-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};qr.getPositions=function(e){let n=[],r=qr.getRowColCoords(e),s=r.length;for(let i=0;i<s;i++)for(let o=0;o<s;o++)i===0&&o===0||i===0&&o===s-1||i===s-1&&o===0||n.push([r[i],r[o]]);return n}});var wc=v(vc=>{var ly=ot().getSymbolSize,Sc=7;vc.getPositions=function(e){let n=ly(e);return[[0,0],[n-Sc,0],[0,n-Sc]]}});var bc=v(q=>{q.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var xt={N1:3,N2:3,N3:40,N4:10};q.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};q.from=function(e){return q.isValid(e)?parseInt(e,10):void 0};q.getPenaltyN1=function(e){let n=e.size,r=0,s=0,i=0,o=null,a=null;for(let l=0;l<n;l++){s=i=0,o=a=null;for(let c=0;c<n;c++){let u=e.get(l,c);u===o?s++:(s>=5&&(r+=xt.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(r+=xt.N1+(i-5)),a=u,i=1)}s>=5&&(r+=xt.N1+(s-5)),i>=5&&(r+=xt.N1+(i-5))}return r};q.getPenaltyN2=function(e){let n=e.size,r=0;for(let s=0;s<n-1;s++)for(let i=0;i<n-1;i++){let o=e.get(s,i)+e.get(s,i+1)+e.get(s+1,i)+e.get(s+1,i+1);(o===4||o===0)&&r++}return r*xt.N2};q.getPenaltyN3=function(e){let n=e.size,r=0,s=0,i=0;for(let o=0;o<n;o++){s=i=0;for(let a=0;a<n;a++)s=s<<1&2047|e.get(o,a),a>=10&&(s===1488||s===93)&&r++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&r++}return r*xt.N3};q.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let i=0;i<r;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/r/5)-10)*xt.N4};function cy(t,e,n){switch(t){case q.Patterns.PATTERN000:return(e+n)%2===0;case q.Patterns.PATTERN001:return e%2===0;case q.Patterns.PATTERN010:return n%3===0;case q.Patterns.PATTERN011:return(e+n)%3===0;case q.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case q.Patterns.PATTERN101:return e*n%2+e*n%3===0;case q.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case q.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}q.applyMask=function(e,n){let r=n.size;for(let s=0;s<r;s++)for(let i=0;i<r;i++)n.isReserved(i,s)||n.xor(i,s,cy(e,i,s))};q.getBestMask=function(e,n){let r=Object.keys(q.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){n(o),q.applyMask(o,e);let a=q.getPenaltyN1(e)+q.getPenaltyN2(e)+q.getPenaltyN3(e)+q.getPenaltyN4(e);q.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var Ri=v(Ti=>{var at=Ur(),$r=[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],Wr=[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];Ti.getBlocksCount=function(e,n){switch(n){case at.L:return $r[(e-1)*4+0];case at.M:return $r[(e-1)*4+1];case at.Q:return $r[(e-1)*4+2];case at.H:return $r[(e-1)*4+3];default:return}};Ti.getTotalCodewordsCount=function(e,n){switch(n){case at.L:return Wr[(e-1)*4+0];case at.M:return Wr[(e-1)*4+1];case at.Q:return Wr[(e-1)*4+2];case at.H:return Wr[(e-1)*4+3];default:return}}});var Ac=v(jr=>{var On=new Uint8Array(512),Gr=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)On[n]=e,Gr[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)On[n]=On[n-255]})();jr.log=function(e){if(e<1)throw new Error("log("+e+")");return Gr[e]};jr.exp=function(e){return On[e]};jr.mul=function(e,n){return e===0||n===0?0:On[Gr[e]+Gr[n]]}});var Ec=v(Dn=>{var ki=Ac();Dn.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<n.length;i++)r[s+i]^=ki.mul(e[s],n[i]);return r};Dn.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let s=r[0];for(let o=0;o<n.length;o++)r[o]^=ki.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};Dn.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=Dn.mul(n,new Uint8Array([1,ki.exp(r)]));return n}});var Cc=v((ZE,xc)=>{var Ic=Ec();function Pi(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Pi.prototype.initialize=function(e){this.degree=e,this.genPoly=Ic.generateECPolynomial(this.degree)};Pi.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=Ic.mod(n,this.genPoly),s=this.degree-r.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(r,s),i}return r};xc.exports=Pi});var Mi=v(Tc=>{Tc.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Li=v(Qe=>{var Rc="[0-9]+",uy="[A-Z $%*+\\-./:]+",Hn="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Hn=Hn.replace(/u/g,"\\u");var dy="(?:(?![A-Z0-9 $%*+\\-./:]|"+Hn+`)(?:.|[\r
8
- ]))+`;Qe.KANJI=new RegExp(Hn,"g");Qe.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Qe.BYTE=new RegExp(dy,"g");Qe.NUMERIC=new RegExp(Rc,"g");Qe.ALPHANUMERIC=new RegExp(uy,"g");var fy=new RegExp("^"+Hn+"$"),hy=new RegExp("^"+Rc+"$"),py=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Qe.testKanji=function(e){return fy.test(e)};Qe.testNumeric=function(e){return hy.test(e)};Qe.testAlphanumeric=function(e){return py.test(e)}});var lt=v(ne=>{var gy=Mi(),Ni=Li();ne.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};ne.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};ne.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};ne.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};ne.MIXED={bit:-1};ne.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!gy.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};ne.getBestModeForData=function(e){return Ni.testNumeric(e)?ne.NUMERIC:Ni.testAlphanumeric(e)?ne.ALPHANUMERIC:Ni.testKanji(e)?ne.KANJI:ne.BYTE};ne.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};ne.isValid=function(e){return e&&e.bit&&e.ccBits};function my(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return ne.NUMERIC;case"alphanumeric":return ne.ALPHANUMERIC;case"kanji":return ne.KANJI;case"byte":return ne.BYTE;default:throw new Error("Unknown mode: "+t)}}ne.from=function(e,n){if(ne.isValid(e))return e;try{return my(e)}catch{return n}}});var Nc=v(Ct=>{var Vr=ot(),yy=Ri(),kc=Ur(),ct=lt(),Oi=Mi(),Mc=7973,Pc=Vr.getBCHDigit(Mc);function _y(t,e,n){for(let r=1;r<=40;r++)if(e<=Ct.getCapacity(r,n,t))return r}function Lc(t,e){return ct.getCharCountIndicator(t,e)+4}function Sy(t,e){let n=0;return t.forEach(function(r){let s=Lc(r.mode,e);n+=s+r.getBitsLength()}),n}function vy(t,e){for(let n=1;n<=40;n++)if(Sy(t,n)<=Ct.getCapacity(n,e,ct.MIXED))return n}Ct.from=function(e,n){return Oi.isValid(e)?parseInt(e,10):n};Ct.getCapacity=function(e,n,r){if(!Oi.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=ct.BYTE);let s=Vr.getSymbolTotalCodewords(e),i=yy.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===ct.MIXED)return o;let a=o-Lc(r,e);switch(r){case ct.NUMERIC:return Math.floor(a/10*3);case ct.ALPHANUMERIC:return Math.floor(a/11*2);case ct.KANJI:return Math.floor(a/13);case ct.BYTE:default:return Math.floor(a/8)}};Ct.getBestVersionForData=function(e,n){let r,s=kc.from(n,kc.M);if(Array.isArray(e)){if(e.length>1)return vy(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return _y(r.mode,r.getLength(),s)};Ct.getEncodedBits=function(e){if(!Oi.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;Vr.getBCHDigit(n)-Pc>=0;)n^=Mc<<Vr.getBCHDigit(n)-Pc;return e<<12|n}});var Bc=v(Hc=>{var Di=ot(),Dc=1335,wy=21522,Oc=Di.getBCHDigit(Dc);Hc.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;Di.getBCHDigit(s)-Oc>=0;)s^=Dc<<Di.getBCHDigit(s)-Oc;return(r<<10|s)^wy}});var Uc=v((iI,Fc)=>{var by=lt();function Kt(t){this.mode=by.NUMERIC,this.data=t.toString()}Kt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Kt.prototype.getLength=function(){return this.data.length};Kt.prototype.getBitsLength=function(){return Kt.getBitsLength(this.data.length)};Kt.prototype.write=function(e){let n,r,s;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),s=parseInt(r,10),e.put(s,10);let i=this.data.length-n;i>0&&(r=this.data.substr(n),s=parseInt(r,10),e.put(s,i*3+1))};Fc.exports=Kt});var $c=v((oI,qc)=>{var Ay=lt(),Hi=["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 Jt(t){this.mode=Ay.ALPHANUMERIC,this.data=t}Jt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Jt.prototype.getLength=function(){return this.data.length};Jt.prototype.getBitsLength=function(){return Jt.getBitsLength(this.data.length)};Jt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=Hi.indexOf(this.data[n])*45;r+=Hi.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(Hi.indexOf(this.data[n]),6)};qc.exports=Jt});var Gc=v((aI,Wc)=>{var Ey=lt();function Qt(t){this.mode=Ey.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Qt.getBitsLength=function(e){return e*8};Qt.prototype.getLength=function(){return this.data.length};Qt.prototype.getBitsLength=function(){return Qt.getBitsLength(this.data.length)};Qt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Wc.exports=Qt});var Vc=v((lI,jc)=>{var Iy=lt(),xy=ot();function Xt(t){this.mode=Iy.KANJI,this.data=t}Xt.getBitsLength=function(e){return e*13};Xt.prototype.getLength=function(){return this.data.length};Xt.prototype.getBitsLength=function(){return Xt.getBitsLength(this.data.length)};Xt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=xy.toSJIS(this.data[e]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
9
- Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};jc.exports=Xt});var zc=v((cI,Bi)=>{"use strict";var Bn={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=Bn.PriorityQueue.make();i.push(e,0);for(var o,a,l,c,u,d,f,p,g;!i.empty();){o=i.pop(),a=o.value,c=o.cost,u=t[a]||{};for(l in u)u.hasOwnProperty(l)&&(d=u[l],f=c+d,p=s[l],g=typeof s[l]>"u",(g||p>f)&&(s[l]=f,i.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var h=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(h)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,s;r;)n.push(r),s=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=Bn.single_source_shortest_paths(t,e,n);return Bn.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Bn.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Bi<"u"&&(Bi.exports=Bn)});var tu=v(Zt=>{var B=lt(),Jc=Uc(),Qc=$c(),Xc=Gc(),Zc=Vc(),Fn=Li(),zr=ot(),Cy=zc();function Yc(t){return unescape(encodeURIComponent(t)).length}function Un(t,e,n){let r=[],s;for(;(s=t.exec(n))!==null;)r.push({data:s[0],index:s.index,mode:e,length:s[0].length});return r}function eu(t){let e=Un(Fn.NUMERIC,B.NUMERIC,t),n=Un(Fn.ALPHANUMERIC,B.ALPHANUMERIC,t),r,s;return zr.isKanjiModeEnabled()?(r=Un(Fn.BYTE,B.BYTE,t),s=Un(Fn.KANJI,B.KANJI,t)):(r=Un(Fn.BYTE_KANJI,B.BYTE,t),s=[]),e.concat(n,r,s).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Fi(t,e){switch(e){case B.NUMERIC:return Jc.getBitsLength(t);case B.ALPHANUMERIC:return Qc.getBitsLength(t);case B.KANJI:return Zc.getBitsLength(t);case B.BYTE:return Xc.getBitsLength(t)}}function Ty(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function Ry(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case B.NUMERIC:e.push([r,{data:r.data,mode:B.ALPHANUMERIC,length:r.length},{data:r.data,mode:B.BYTE,length:r.length}]);break;case B.ALPHANUMERIC:e.push([r,{data:r.data,mode:B.BYTE,length:r.length}]);break;case B.KANJI:e.push([r,{data:r.data,mode:B.BYTE,length:Yc(r.data)}]);break;case B.BYTE:e.push([{data:r.data,mode:B.BYTE,length:Yc(r.data)}])}}return e}function ky(t,e){let n={},r={start:{}},s=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let c=o[l],u=""+i+l;a.push(u),n[u]={node:c,lastCount:0},r[u]={};for(let d=0;d<s.length;d++){let f=s[d];n[f]&&n[f].node.mode===c.mode?(r[f][u]=Fi(n[f].lastCount+c.length,c.mode)-Fi(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=Fi(c.length,c.mode)+4+B.getCharCountIndicator(c.mode,e))}}s=a}for(let i=0;i<s.length;i++)r[s[i]].end=0;return{map:r,table:n}}function Kc(t,e){let n,r=B.getBestModeForData(t);if(n=B.from(e,r),n!==B.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+B.toString(n)+`.
10
- Suggested mode is: `+B.toString(r));switch(n===B.KANJI&&!zr.isKanjiModeEnabled()&&(n=B.BYTE),n){case B.NUMERIC:return new Jc(t);case B.ALPHANUMERIC:return new Qc(t);case B.KANJI:return new Zc(t);case B.BYTE:return new Xc(t)}}Zt.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(Kc(r,null)):r.data&&n.push(Kc(r.data,r.mode)),n},[])};Zt.fromString=function(e,n){let r=eu(e,zr.isKanjiModeEnabled()),s=Ry(r),i=ky(s,n),o=Cy.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return Zt.fromArray(Ty(a))};Zt.rawSplit=function(e){return Zt.fromArray(eu(e,zr.isKanjiModeEnabled()))}});var ji=v(nu=>{var Kr=ot(),Ui=Ur(),Py=gc(),My=yc(),Ly=_c(),Ny=wc(),Wi=bc(),Gi=Ri(),Oy=Cc(),Yr=Nc(),Dy=Bc(),Hy=lt(),qi=tu();function By(t,e){let n=t.size,r=Ny.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(i+a,o+l,!0,!0):t.set(i+a,o+l,!1,!0))}}function Fy(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function Uy(t,e){let n=Ly.getPositions(e);for(let r=0;r<n.length;r++){let s=n[r][0],i=n[r][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(s+o,i+a,!0,!0):t.set(s+o,i+a,!1,!0)}}function qy(t,e){let n=t.size,r=Yr.getEncodedBits(e),s,i,o;for(let a=0;a<18;a++)s=Math.floor(a/3),i=a%3+n-8-3,o=(r>>a&1)===1,t.set(s,i,o,!0),t.set(i,s,o,!0)}function $i(t,e,n){let r=t.size,s=Dy.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(r-15+i,8,o,!0),i<8?t.set(8,r-i-1,o,!0):i<9?t.set(8,15-i-1+1,o,!0):t.set(8,15-i-1,o,!0);t.set(r-8,8,1,!0)}function $y(t,e){let n=t.size,r=-1,s=n-1,i=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(s,a-l)){let c=!1;o<e.length&&(c=(e[o]>>>i&1)===1),t.set(s,a-l,c),i--,i===-1&&(o++,i=7)}if(s+=r,s<0||n<=s){s-=r,r=-r;break}}}function Wy(t,e,n){let r=new Py;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),Hy.getCharCountIndicator(l.mode,t)),l.write(r)});let s=Kr.getSymbolTotalCodewords(t),i=Gi.getTotalCodewordsCount(t,e),o=(s-i)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(o-r.getLengthInBits())/8;for(let l=0;l<a;l++)r.put(l%2?17:236,8);return Gy(r,t,e)}function Gy(t,e,n){let r=Kr.getSymbolTotalCodewords(e),s=Gi.getTotalCodewordsCount(e,n),i=r-s,o=Gi.getBlocksCount(e,n),a=r%o,l=o-a,c=Math.floor(r/o),u=Math.floor(i/o),d=u+1,f=c-u,p=new Oy(f),g=0,h=new Array(o),_=new Array(o),w=0,E=new Uint8Array(t.buffer);for(let U=0;U<o;U++){let x=U<l?u:d;h[U]=E.slice(g,g+x),_[U]=p.encode(h[U]),g+=x,w=Math.max(w,x)}let L=new Uint8Array(r),N=0,O,X;for(O=0;O<w;O++)for(X=0;X<o;X++)O<h[X].length&&(L[N++]=h[X][O]);for(O=0;O<f;O++)for(X=0;X<o;X++)L[N++]=_[X][O];return L}function jy(t,e,n,r){let s;if(Array.isArray(t))s=qi.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=qi.rawSplit(t);c=Yr.getBestVersionForData(u,n)}s=qi.fromString(t,c||40)}else throw new Error("Invalid data");let i=Yr.getBestVersionForData(s,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
7
+ `+n)}function We(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,We),t.emit("wsClientError",o,n,e)}else Gt(n,r,s,i)}});var rs=y((hv,$o)=>{$o.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Te=y(Ge=>{var ss,qf=[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];Ge.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};Ge.getSymbolTotalCodewords=function(e){return qf[e]};Ge.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Ge.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');ss=e};Ge.isKanjiModeEnabled=function(){return typeof ss<"u"};Ge.toSJIS=function(e){return ss(e)}});var Hn=y(ee=>{ee.L={bit:1};ee.M={bit:0};ee.Q={bit:3};ee.H={bit:2};function Wf(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ee.L;case"m":case"medium":return ee.M;case"q":case"quartile":return ee.Q;case"h":case"high":return ee.H;default:throw new Error("Unknown EC Level: "+t)}}ee.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ee.from=function(e,n){if(ee.isValid(e))return e;try{return Wf(e)}catch{return n}}});var Jo=y((yv,Yo)=>{function zo(){this.buffer=[],this.length=0}zo.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 n=0;n<e;n++)this.putBit((t>>>e-n-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++}};Yo.exports=zo});var Qo=y((vv,Ko)=>{function jt(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)}jt.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};jt.prototype.get=function(t,e){return this.data[t*this.size+e]};jt.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};jt.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Ko.exports=jt});var Xo=y(Fn=>{var Gf=Te().getSymbolSize;Fn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=Gf(e),s=r===145?26:Math.ceil((r-13)/(2*n-2))*2,i=[r-7];for(let o=1;o<n-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};Fn.getPositions=function(e){let n=[],r=Fn.getRowColCoords(e),s=r.length;for(let i=0;i<s;i++)for(let o=0;o<s;o++)i===0&&o===0||i===0&&o===s-1||i===s-1&&o===0||n.push([r[i],r[o]]);return n}});var ta=y(ea=>{var jf=Te().getSymbolSize,Zo=7;ea.getPositions=function(e){let n=jf(e);return[[0,0],[n-Zo,0],[0,n-Zo]]}});var na=y(T=>{T.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var je={N1:3,N2:3,N3:40,N4:10};T.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};T.from=function(e){return T.isValid(e)?parseInt(e,10):void 0};T.getPenaltyN1=function(e){let n=e.size,r=0,s=0,i=0,o=null,a=null;for(let l=0;l<n;l++){s=i=0,o=a=null;for(let c=0;c<n;c++){let u=e.get(l,c);u===o?s++:(s>=5&&(r+=je.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(r+=je.N1+(i-5)),a=u,i=1)}s>=5&&(r+=je.N1+(s-5)),i>=5&&(r+=je.N1+(i-5))}return r};T.getPenaltyN2=function(e){let n=e.size,r=0;for(let s=0;s<n-1;s++)for(let i=0;i<n-1;i++){let o=e.get(s,i)+e.get(s,i+1)+e.get(s+1,i)+e.get(s+1,i+1);(o===4||o===0)&&r++}return r*je.N2};T.getPenaltyN3=function(e){let n=e.size,r=0,s=0,i=0;for(let o=0;o<n;o++){s=i=0;for(let a=0;a<n;a++)s=s<<1&2047|e.get(o,a),a>=10&&(s===1488||s===93)&&r++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&r++}return r*je.N3};T.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let i=0;i<r;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/r/5)-10)*je.N4};function Vf(t,e,n){switch(t){case T.Patterns.PATTERN000:return(e+n)%2===0;case T.Patterns.PATTERN001:return e%2===0;case T.Patterns.PATTERN010:return n%3===0;case T.Patterns.PATTERN011:return(e+n)%3===0;case T.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case T.Patterns.PATTERN101:return e*n%2+e*n%3===0;case T.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case T.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}T.applyMask=function(e,n){let r=n.size;for(let s=0;s<r;s++)for(let i=0;i<r;i++)n.isReserved(i,s)||n.xor(i,s,Vf(e,i,s))};T.getBestMask=function(e,n){let r=Object.keys(T.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){n(o),T.applyMask(o,e);let a=T.getPenaltyN1(e)+T.getPenaltyN2(e)+T.getPenaltyN3(e)+T.getPenaltyN4(e);T.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var os=y(is=>{var xe=Hn(),Un=[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],qn=[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];is.getBlocksCount=function(e,n){switch(n){case xe.L:return Un[(e-1)*4+0];case xe.M:return Un[(e-1)*4+1];case xe.Q:return Un[(e-1)*4+2];case xe.H:return Un[(e-1)*4+3];default:return}};is.getTotalCodewordsCount=function(e,n){switch(n){case xe.L:return qn[(e-1)*4+0];case xe.M:return qn[(e-1)*4+1];case xe.Q:return qn[(e-1)*4+2];case xe.H:return qn[(e-1)*4+3];default:return}}});var ra=y(Gn=>{var Vt=new Uint8Array(512),Wn=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)Vt[n]=e,Wn[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)Vt[n]=Vt[n-255]})();Gn.log=function(e){if(e<1)throw new Error("log("+e+")");return Wn[e]};Gn.exp=function(e){return Vt[e]};Gn.mul=function(e,n){return e===0||n===0?0:Vt[Wn[e]+Wn[n]]}});var sa=y($t=>{var as=ra();$t.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<n.length;i++)r[s+i]^=as.mul(e[s],n[i]);return r};$t.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let s=r[0];for(let o=0;o<n.length;o++)r[o]^=as.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};$t.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=$t.mul(n,new Uint8Array([1,as.exp(r)]));return n}});var aa=y((Tv,oa)=>{var ia=sa();function ls(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}ls.prototype.initialize=function(e){this.degree=e,this.genPoly=ia.generateECPolynomial(this.degree)};ls.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=ia.mod(n,this.genPoly),s=this.degree-r.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(r,s),i}return r};oa.exports=ls});var cs=y(la=>{la.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var us=y(Se=>{var ca="[0-9]+",$f="[A-Z $%*+\\-./:]+",zt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";zt=zt.replace(/u/g,"\\u");var zf="(?:(?![A-Z0-9 $%*+\\-./:]|"+zt+`)(?:.|[\r
8
+ ]))+`;Se.KANJI=new RegExp(zt,"g");Se.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Se.BYTE=new RegExp(zf,"g");Se.NUMERIC=new RegExp(ca,"g");Se.ALPHANUMERIC=new RegExp($f,"g");var Yf=new RegExp("^"+zt+"$"),Jf=new RegExp("^"+ca+"$"),Kf=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Se.testKanji=function(e){return Yf.test(e)};Se.testNumeric=function(e){return Jf.test(e)};Se.testAlphanumeric=function(e){return Kf.test(e)}});var Ce=y(O=>{var Qf=cs(),ds=us();O.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};O.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};O.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};O.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};O.MIXED={bit:-1};O.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Qf.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};O.getBestModeForData=function(e){return ds.testNumeric(e)?O.NUMERIC:ds.testAlphanumeric(e)?O.ALPHANUMERIC:ds.testKanji(e)?O.KANJI:O.BYTE};O.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};O.isValid=function(e){return e&&e.bit&&e.ccBits};function Xf(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return O.NUMERIC;case"alphanumeric":return O.ALPHANUMERIC;case"kanji":return O.KANJI;case"byte":return O.BYTE;default:throw new Error("Unknown mode: "+t)}}O.from=function(e,n){if(O.isValid(e))return e;try{return Xf(e)}catch{return n}}});var ha=y(Ve=>{var jn=Te(),Zf=os(),ua=Hn(),ke=Ce(),fs=cs(),fa=7973,da=jn.getBCHDigit(fa);function ep(t,e,n){for(let r=1;r<=40;r++)if(e<=Ve.getCapacity(r,n,t))return r}function pa(t,e){return ke.getCharCountIndicator(t,e)+4}function tp(t,e){let n=0;return t.forEach(function(r){let s=pa(r.mode,e);n+=s+r.getBitsLength()}),n}function np(t,e){for(let n=1;n<=40;n++)if(tp(t,n)<=Ve.getCapacity(n,e,ke.MIXED))return n}Ve.from=function(e,n){return fs.isValid(e)?parseInt(e,10):n};Ve.getCapacity=function(e,n,r){if(!fs.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=ke.BYTE);let s=jn.getSymbolTotalCodewords(e),i=Zf.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===ke.MIXED)return o;let a=o-pa(r,e);switch(r){case ke.NUMERIC:return Math.floor(a/10*3);case ke.ALPHANUMERIC:return Math.floor(a/11*2);case ke.KANJI:return Math.floor(a/13);case ke.BYTE:default:return Math.floor(a/8)}};Ve.getBestVersionForData=function(e,n){let r,s=ua.from(n,ua.M);if(Array.isArray(e)){if(e.length>1)return np(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return ep(r.mode,r.getLength(),s)};Ve.getEncodedBits=function(e){if(!fs.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;jn.getBCHDigit(n)-da>=0;)n^=fa<<jn.getBCHDigit(n)-da;return e<<12|n}});var va=y(ya=>{var ps=Te(),ma=1335,rp=21522,ga=ps.getBCHDigit(ma);ya.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;ps.getBCHDigit(s)-ga>=0;)s^=ma<<ps.getBCHDigit(s)-ga;return(r<<10|s)^rp}});var _a=y((Rv,Sa)=>{var sp=Ce();function dt(t){this.mode=sp.NUMERIC,this.data=t.toString()}dt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};dt.prototype.getLength=function(){return this.data.length};dt.prototype.getBitsLength=function(){return dt.getBitsLength(this.data.length)};dt.prototype.write=function(e){let n,r,s;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),s=parseInt(r,10),e.put(s,10);let i=this.data.length-n;i>0&&(r=this.data.substr(n),s=parseInt(r,10),e.put(s,i*3+1))};Sa.exports=dt});var wa=y((Mv,ba)=>{var ip=Ce(),hs=["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 ft(t){this.mode=ip.ALPHANUMERIC,this.data=t}ft.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};ft.prototype.getLength=function(){return this.data.length};ft.prototype.getBitsLength=function(){return ft.getBitsLength(this.data.length)};ft.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=hs.indexOf(this.data[n])*45;r+=hs.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(hs.indexOf(this.data[n]),6)};ba.exports=ft});var Aa=y((Lv,Ia)=>{var op=Ce();function pt(t){this.mode=op.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}pt.getBitsLength=function(e){return e*8};pt.prototype.getLength=function(){return this.data.length};pt.prototype.getBitsLength=function(){return pt.getBitsLength(this.data.length)};pt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Ia.exports=pt});var xa=y((Nv,Ta)=>{var ap=Ce(),lp=Te();function ht(t){this.mode=ap.KANJI,this.data=t}ht.getBitsLength=function(e){return e*13};ht.prototype.getLength=function(){return this.data.length};ht.prototype.getBitsLength=function(){return ht.getBitsLength(this.data.length)};ht.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=lp.toSJIS(this.data[e]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
9
+ Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};Ta.exports=ht});var Ca=y((Ov,gs)=>{"use strict";var Yt={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=Yt.PriorityQueue.make();i.push(e,0);for(var o,a,l,c,u,d,f,h,g;!i.empty();){o=i.pop(),a=o.value,c=o.cost,u=t[a]||{};for(l in u)u.hasOwnProperty(l)&&(d=u[l],f=c+d,h=s[l],g=typeof s[l]>"u",(g||h>f)&&(s[l]=f,i.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var p=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(p)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,s;r;)n.push(r),s=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=Yt.single_source_shortest_paths(t,e,n);return Yt.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Yt.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof gs<"u"&&(gs.exports=Yt)});var Oa=y(gt=>{var A=Ce(),Pa=_a(),Ra=wa(),Ma=Aa(),La=xa(),Jt=us(),Vn=Te(),cp=Ca();function ka(t){return unescape(encodeURIComponent(t)).length}function Kt(t,e,n){let r=[],s;for(;(s=t.exec(n))!==null;)r.push({data:s[0],index:s.index,mode:e,length:s[0].length});return r}function Na(t){let e=Kt(Jt.NUMERIC,A.NUMERIC,t),n=Kt(Jt.ALPHANUMERIC,A.ALPHANUMERIC,t),r,s;return Vn.isKanjiModeEnabled()?(r=Kt(Jt.BYTE,A.BYTE,t),s=Kt(Jt.KANJI,A.KANJI,t)):(r=Kt(Jt.BYTE_KANJI,A.BYTE,t),s=[]),e.concat(n,r,s).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function ms(t,e){switch(e){case A.NUMERIC:return Pa.getBitsLength(t);case A.ALPHANUMERIC:return Ra.getBitsLength(t);case A.KANJI:return La.getBitsLength(t);case A.BYTE:return Ma.getBitsLength(t)}}function up(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function dp(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case A.NUMERIC:e.push([r,{data:r.data,mode:A.ALPHANUMERIC,length:r.length},{data:r.data,mode:A.BYTE,length:r.length}]);break;case A.ALPHANUMERIC:e.push([r,{data:r.data,mode:A.BYTE,length:r.length}]);break;case A.KANJI:e.push([r,{data:r.data,mode:A.BYTE,length:ka(r.data)}]);break;case A.BYTE:e.push([{data:r.data,mode:A.BYTE,length:ka(r.data)}])}}return e}function fp(t,e){let n={},r={start:{}},s=["start"];for(let i=0;i<t.length;i++){let o=t[i],a=[];for(let l=0;l<o.length;l++){let c=o[l],u=""+i+l;a.push(u),n[u]={node:c,lastCount:0},r[u]={};for(let d=0;d<s.length;d++){let f=s[d];n[f]&&n[f].node.mode===c.mode?(r[f][u]=ms(n[f].lastCount+c.length,c.mode)-ms(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=ms(c.length,c.mode)+4+A.getCharCountIndicator(c.mode,e))}}s=a}for(let i=0;i<s.length;i++)r[s[i]].end=0;return{map:r,table:n}}function Ea(t,e){let n,r=A.getBestModeForData(t);if(n=A.from(e,r),n!==A.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+A.toString(n)+`.
10
+ Suggested mode is: `+A.toString(r));switch(n===A.KANJI&&!Vn.isKanjiModeEnabled()&&(n=A.BYTE),n){case A.NUMERIC:return new Pa(t);case A.ALPHANUMERIC:return new Ra(t);case A.KANJI:return new La(t);case A.BYTE:return new Ma(t)}}gt.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(Ea(r,null)):r.data&&n.push(Ea(r.data,r.mode)),n},[])};gt.fromString=function(e,n){let r=Na(e,Vn.isKanjiModeEnabled()),s=dp(r),i=fp(s,n),o=cp.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return gt.fromArray(up(a))};gt.rawSplit=function(e){return gt.fromArray(Na(e,Vn.isKanjiModeEnabled()))}});var ws=y(Ba=>{var zn=Te(),ys=Hn(),pp=Jo(),hp=Qo(),gp=Xo(),mp=ta(),_s=na(),bs=os(),yp=aa(),$n=ha(),vp=va(),Sp=Ce(),vs=Oa();function _p(t,e){let n=t.size,r=mp.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let l=-1;l<=7;l++)o+l<=-1||n<=o+l||(a>=0&&a<=6&&(l===0||l===6)||l>=0&&l<=6&&(a===0||a===6)||a>=2&&a<=4&&l>=2&&l<=4?t.set(i+a,o+l,!0,!0):t.set(i+a,o+l,!1,!0))}}function bp(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function wp(t,e){let n=gp.getPositions(e);for(let r=0;r<n.length;r++){let s=n[r][0],i=n[r][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?t.set(s+o,i+a,!0,!0):t.set(s+o,i+a,!1,!0)}}function Ip(t,e){let n=t.size,r=$n.getEncodedBits(e),s,i,o;for(let a=0;a<18;a++)s=Math.floor(a/3),i=a%3+n-8-3,o=(r>>a&1)===1,t.set(s,i,o,!0),t.set(i,s,o,!0)}function Ss(t,e,n){let r=t.size,s=vp.getEncodedBits(e,n),i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?t.set(i,8,o,!0):i<8?t.set(i+1,8,o,!0):t.set(r-15+i,8,o,!0),i<8?t.set(8,r-i-1,o,!0):i<9?t.set(8,15-i-1+1,o,!0):t.set(8,15-i-1,o,!0);t.set(r-8,8,1,!0)}function Ap(t,e){let n=t.size,r=-1,s=n-1,i=7,o=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let l=0;l<2;l++)if(!t.isReserved(s,a-l)){let c=!1;o<e.length&&(c=(e[o]>>>i&1)===1),t.set(s,a-l,c),i--,i===-1&&(o++,i=7)}if(s+=r,s<0||n<=s){s-=r,r=-r;break}}}function Tp(t,e,n){let r=new pp;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),Sp.getCharCountIndicator(l.mode,t)),l.write(r)});let s=zn.getSymbolTotalCodewords(t),i=bs.getTotalCodewordsCount(t,e),o=(s-i)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(o-r.getLengthInBits())/8;for(let l=0;l<a;l++)r.put(l%2?17:236,8);return xp(r,t,e)}function xp(t,e,n){let r=zn.getSymbolTotalCodewords(e),s=bs.getTotalCodewordsCount(e,n),i=r-s,o=bs.getBlocksCount(e,n),a=r%o,l=o-a,c=Math.floor(r/o),u=Math.floor(i/o),d=u+1,f=c-u,h=new yp(f),g=0,p=new Array(o),m=new Array(o),v=0,b=new Uint8Array(t.buffer);for(let ue=0;ue<o;ue++){let nt=ue<l?u:d;p[ue]=b.slice(g,g+nt),m[ue]=h.encode(p[ue]),g+=nt,v=Math.max(v,nt)}let K=new Uint8Array(r),C=0,H,Q;for(H=0;H<v;H++)for(Q=0;Q<o;Q++)H<p[Q].length&&(K[C++]=p[Q][H]);for(H=0;H<f;H++)for(Q=0;Q<o;Q++)K[C++]=m[Q][H];return K}function Cp(t,e,n,r){let s;if(Array.isArray(t))s=vs.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=vs.rawSplit(t);c=$n.getBestVersionForData(u,n)}s=vs.fromString(t,c||40)}else throw new Error("Invalid data");let i=$n.getBestVersionForData(s,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
11
11
  The chosen QR Code version cannot contain this amount of data.
12
12
  Minimum version required to store current data is: `+i+`.
13
- `);let o=Wy(e,n,s),a=Kr.getSymbolSize(e),l=new My(a);return By(l,e),Fy(l),Uy(l,e),$i(l,n,0),e>=7&&qy(l,e),$y(l,o),isNaN(r)&&(r=Wi.getBestMask(l,$i.bind(null,l,n))),Wi.applyMask(r,l),$i(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}nu.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=Ui.M,s,i;return typeof n<"u"&&(r=Ui.from(n.errorCorrectionLevel,Ui.M),s=Yr.from(n.version),i=Wi.from(n.maskPattern),n.toSJISFunc&&Kr.setToSJISFunction(n.toSJISFunc)),jy(e,s,r,i)}});var Vi=v((fI,su)=>{"use strict";var Vy=require("util"),ru=require("stream"),Ne=su.exports=function(){ru.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Vy.inherits(Ne,ru);Ne.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))};Ne.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};Ne.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()))};Ne.prototype.destroySoon=Ne.prototype.end;Ne.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};Ne.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};Ne.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))};Ne.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,r=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],i=Math.min(s.length,t.length-e);s.copy(r,e,0,i),e+=i,i!==s.length&&(this._buffers[--n]=s.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,r)};Ne.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 Yi=v(zi=>{"use strict";var ut=[{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]}];zi.getImagePasses=function(t,e){let n=[],r=t%8,s=e%8,i=(t-r)/8,o=(e-s)/8;for(let a=0;a<ut.length;a++){let l=ut[a],c=i*l.x.length,u=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<r;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};zi.getInterlaceIterator=function(t){return function(e,n,r){let s=e%ut[r].x.length,i=(e-s)/ut[r].x.length*8+ut[r].x[s],o=n%ut[r].y.length,a=(n-o)/ut[r].y.length*8+ut[r].y[o];return i*4+a*t*4}}});var Ki=v((pI,iu)=>{"use strict";iu.exports=function(e,n,r){let s=e+n-r,i=Math.abs(s-e),o=Math.abs(s-n),a=Math.abs(s-r);return i<=o&&i<=a?e:o<=a?n:r}});var Ji=v((gI,au)=>{"use strict";var zy=Yi(),Yy=Ki();function ou(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var en=au.exports=function(t,e){let n=t.width,r=t.height,s=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=zy.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:ou(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:ou(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};en.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};en.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,s=r-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>s?e[i-r]:0;e[i]=o+a}};en.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let s=0;s<n;s++){let i=t[1+s],o=r?r[s]:0;e[s]=i+o}};en.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=Math.floor((c+l)/2);e[o]=a+u}};en.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=o>s&&i?i[o-r]:0,d=Yy(c,l,u);e[o]=a+d}};en.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],s=r.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var uu=v((mI,cu)=>{"use strict";var Ky=require("util"),lu=Vi(),Jy=Ji(),Qy=cu.exports=function(t){lu.call(this);let e=[],n=this;this._filter=new Jy(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Ky.inherits(Qy,lu)});var tn=v((yI,du)=>{"use strict";du.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 Zi=v((_I,fu)=>{"use strict";var Qi=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;Qi[t]=e}})();var Xi=fu.exports=function(){this._crc=-1};Xi.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Qi[(this._crc^t[e])&255]^this._crc>>>8;return!0};Xi.prototype.crc32=function(){return this._crc^-1};Xi.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Qi[(e^t[n])&255]^e>>>8;return e^-1}});var eo=v((SI,hu)=>{"use strict";var ie=tn(),Xy=Zi(),le=hu.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[ie.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[ie.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[ie.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[ie.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[ie.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[ie.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(){}};le.prototype.start=function(){this.read(ie.PNG_SIGNATURE.length,this._parseSignature.bind(this))};le.prototype._parseSignature=function(t){let e=ie.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};le.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let i=4;i<8;i++)r+=String.fromCharCode(t[i]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==ie.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Xy,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};le.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};le.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};le.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};le.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};le.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],s=t[9],i=t[10],o=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(new Error("Unsupported bit depth "+r));return}if(!(s in ie.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=ie.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&ie.COLORTYPE_PALETTE),color:!!(s&ie.COLORTYPE_COLOR),alpha:!!(s&ie.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};le.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};le.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};le.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};le.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===ie.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===ie.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===ie.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};le.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};le.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/ie.GAMMA_DIVISION),this._handleChunkEnd()};le.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};le.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===ie.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};le.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};le.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var to=v(gu=>{"use strict";var pu=Yi(),Zy=[function(){},function(t,e,n,r){if(r===e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],e_=[function(){},function(t,e,n,r){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function t_(t,e){let n=[],r=0;function s(){if(r===t.length)throw new Error("Ran out of data");let i=t[r];r++;let o,a,l,c,u,d,f,p;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[r],r++,n.push((i<<8)+f);break;case 4:f=i&15,p=i>>4,n.push(p,f);break;case 2:u=i&3,d=i>>2&3,f=i>>4&3,p=i>>6&3,n.push(p,f,d,u);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,c=i>>3&1,u=i>>4&1,d=i>>5&1,f=i>>6&1,p=i>>7&1,n.push(p,f,d,u,c,l,a,o);break}}return{get:function(i){for(;n.length<i;)s();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw new Error("extra data found")}}}function n_(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<o;u++){let d=n(u,c,l);Zy[r](e,s,d,i),i+=r}return i}function r_(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<o;u++){let d=s.get(r),f=n(u,c,l);e_[r](e,d,f,i)}s.resetAfterLine()}}gu.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=t_(t,s));let l;s<=8?l=Buffer.alloc(n*r*4):l=new Uint16Array(n*r*4);let c=Math.pow(2,s)-1,u=0,d,f;if(o)d=pu.getImagePasses(n,r),f=pu.getInterlaceIterator(n,r);else{let p=0;f=function(){let g=p;return p+=4,g},d=[{width:n,height:r}]}for(let p=0;p<d.length;p++)s===8?u=n_(d[p],l,f,i,t,u):r_(d[p],l,f,i,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var no=v((wI,mu)=>{"use strict";function s_(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=s[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let c=0;c<4;c++)e[i+c]=l[c];i+=4}}function i_(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[i]&&(l=!0):s[0]===t[i]&&s[1]===t[i+1]&&s[2]===t[i+2]&&(l=!0),l)for(let c=0;c<4;c++)e[i+c]=0;i+=4}}function o_(t,e,n,r,s){let i=255,o=Math.pow(2,s)-1,a=0;for(let l=0;l<r;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*i/o+.5);a+=4}}mu.exports=function(t,e){let n=e.depth,r=e.width,s=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?s_(t,l,r,s,a):(o&&i_(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),o_(t,l,r,s,n))),l}});var Su=v((bI,_u)=>{"use strict";var a_=require("util"),ro=require("zlib"),yu=Vi(),l_=uu(),c_=eo(),u_=to(),d_=no(),We=_u.exports=function(t){yu.call(this),this._parser=new c_(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()};a_.inherits(We,yu);We.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};We.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=ro.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 n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,ro.Z_MIN_CHUNK);this._inflate=ro.createInflate({chunkSize:r});let s=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};We.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new l_(this._bitmapInfo)};We.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};We.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};We.prototype._simpleTransparency=function(){this._metaData.alpha=!0};We.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};We.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};We.prototype._complete=function(t){if(this.errord)return;let e;try{let n=u_.dataToBitMap(t,this._bitmapInfo);e=d_(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var wu=v((AI,vu)=>{"use strict";var Re=tn();vu.exports=function(t,e,n,r){let s=[Re.COLORTYPE_COLOR_ALPHA,Re.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=(function(){let h=new ArrayBuffer(2);return new DataView(h).setInt16(0,256,!0),new Int16Array(h)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&g)return t}let i=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=Re.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=Re.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,d=0,f=r.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function p(){let g,h,_,w=o;switch(r.inputColorType){case Re.COLORTYPE_COLOR_ALPHA:w=i[u+3],g=i[u],h=i[u+1],_=i[u+2];break;case Re.COLORTYPE_COLOR:g=i[u],h=i[u+1],_=i[u+2];break;case Re.COLORTYPE_ALPHA:w=i[u+1],g=i[u],h=g,_=g;break;case Re.COLORTYPE_GRAYSCALE:g=i[u],h=g,_=g;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(w/=o,g=Math.min(Math.max(Math.round((1-w)*f.red+w*g),0),o),h=Math.min(Math.max(Math.round((1-w)*f.green+w*h),0),o),_=Math.min(Math.max(Math.round((1-w)*f.blue+w*_),0),o))),{red:g,green:h,blue:_,alpha:w}}for(let g=0;g<n;g++)for(let h=0;h<e;h++){let _=p(i,u);switch(r.colorType){case Re.COLORTYPE_COLOR_ALPHA:case Re.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=_.red,c[d+1]=_.green,c[d+2]=_.blue,s&&(c[d+3]=_.alpha)):(c.writeUInt16BE(_.red,d),c.writeUInt16BE(_.green,d+2),c.writeUInt16BE(_.blue,d+4),s&&c.writeUInt16BE(_.alpha,d+6));break;case Re.COLORTYPE_ALPHA:case Re.COLORTYPE_GRAYSCALE:{let w=(_.red+_.green+_.blue)/3;r.bitDepth===8?(c[d]=w,s&&(c[d+1]=_.alpha)):(c.writeUInt16BE(w,d),s&&c.writeUInt16BE(_.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var Eu=v((EI,Au)=>{"use strict";var bu=Ki();function f_(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function h_(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function p_(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;r[s+o]=l}}function g_(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=t[e+i]-o;s+=Math.abs(a)}return s}function m_(t,e,n,r,s){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;r[s+i]=a}}function y_(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++){let o=e>0?t[i-n]:0,a=t[i]-o;r+=Math.abs(a)}return r}function __(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=t[e+o]-(a+l>>1);r[s+o]=c}}function S_(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function v_(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=e>0&&o>=i?t[e+o-(n+i)]:0,u=t[e+o]-bu(a,l,c);r[s+o]=u}}function w_(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=r?t[e+i-(n+r)]:0,c=t[e+i]-bu(o,a,l);s+=Math.abs(c)}return s}var b_={0:f_,1:p_,2:m_,3:__,4:v_},A_={0:h_,1:g_,2:y_,3:S_,4:w_};Au.exports=function(t,e,n,r,s){let i;if(!("filterType"in r)||r.filterType===-1)i=[0,1,2,3,4];else if(typeof r.filterType=="number")i=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(s*=2);let o=e*s,a=0,l=0,c=Buffer.alloc((o+1)*n),u=i[0];for(let d=0;d<n;d++){if(i.length>1){let f=1/0;for(let p=0;p<i.length;p++){let g=A_[i[p]](t,l,o,s);g<f&&(u=i[p],f=g)}}c[a]=u,a++,b_[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var so=v((II,Iu)=>{"use strict";var fe=tn(),E_=Zi(),I_=wu(),x_=Eu(),C_=require("zlib"),dt=Iu.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||C_.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:fe.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:fe.COLORTYPE_COLOR_ALPHA,[fe.COLORTYPE_GRAYSCALE,fe.COLORTYPE_COLOR,fe.COLORTYPE_COLOR_ALPHA,fe.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([fe.COLORTYPE_GRAYSCALE,fe.COLORTYPE_COLOR,fe.COLORTYPE_COLOR_ALPHA,fe.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")};dt.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};dt.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};dt.prototype.filterData=function(t,e,n){let r=I_(t,e,n,this._options),s=fe.COLORTYPE_TO_BPP_MAP[this._options.colorType];return x_(r,e,n,this._options,s)};dt.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e&&e.copy(r,8),r.writeInt32BE(E_.crc32(r.slice(4,r.length-4)),r.length-4),r};dt.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*fe.GAMMA_DIVISION),0),this._packChunk(fe.TYPE_gAMA,e)};dt.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(fe.TYPE_IHDR,n)};dt.prototype.packIDAT=function(t){return this._packChunk(fe.TYPE_IDAT,t)};dt.prototype.packIEND=function(){return this._packChunk(fe.TYPE_IEND,null)}});var Ru=v((xI,Tu)=>{"use strict";var T_=require("util"),xu=require("stream"),R_=tn(),k_=so(),Cu=Tu.exports=function(t){xu.call(this);let e=t||{};this._packer=new k_(e),this._deflate=this._packer.createDeflate(),this.readable=!0};T_.inherits(Cu,xu);Cu.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(R_.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r&&this.emit("data",this._packer.packGAMA(r));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var Ou=v((qn,Nu)=>{"use strict";var ku=require("assert").ok,nn=require("zlib"),P_=require("util"),Pu=require("buffer").kMaxLength;function Tt(t){if(!(this instanceof Tt))return new Tt(t);t&&t.chunkSize<nn.Z_MIN_CHUNK&&(t.chunkSize=nn.Z_MIN_CHUNK),nn.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 M_(t){return new Tt(t)}function Mu(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Tt.prototype._processChunk=function(t,e,n){if(typeof n=="function")return nn.Inflate._processChunk.call(this,t,e,n);let r=this,s=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(g){u=g});function d(g,h){if(r._hadError)return;let _=i-h;if(ku(_>=0,"have should not go down"),_>0){let w=r._buffer.slice(r._offset,r._offset+_);if(r._offset+=_,w.length>o&&(w=w.slice(0,o)),l.push(w),c+=w.length,o-=w.length,o===0)return!1}return(h===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),h===0?(a+=s-g,s=g,!0):!1}ku(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=Pu)throw Mu(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Pu.toString(16)+" bytes");let p=Buffer.concat(l,c);return Mu(this),p};P_.inherits(Tt,nn.Inflate);function L_(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=nn.Z_FINISH),t._processChunk(e,n)}function Lu(t,e){return L_(new Tt(e),t)}Nu.exports=qn=Lu;qn.Inflate=Tt;qn.createInflate=M_;qn.inflateSync=Lu});var io=v((CI,Hu)=>{"use strict";var Du=Hu.exports=function(t){this._buffer=t,this._reads=[]};Du.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Du.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 Fu=v(Bu=>{"use strict";var N_=io(),O_=Ji();Bu.process=function(t,e){let n=[],r=new N_(t);return new O_(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Wu=v((RI,$u)=>{"use strict";var Uu=!0,qu=require("zlib"),D_=Ou();qu.deflateSync||(Uu=!1);var H_=io(),B_=Fu(),F_=eo(),U_=to(),q_=no();$u.exports=function(t,e){if(!Uu)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(N){n=N}let s;function i(N){s=N}function o(N){s.transColor=N}function a(N){s.palette=N}function l(){s.alpha=!0}let c;function u(N){c=N}let d=[];function f(N){d.push(N)}let p=new H_(t);if(new F_(e,{read:p.read.bind(p),error:r,metadata:i,gamma:u,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),p.process(),n)throw n;let h=Buffer.concat(d);d.length=0;let _;if(s.interlace)_=qu.inflateSync(h);else{let O=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;_=D_(h,{chunkSize:O,maxLength:O})}if(h=null,!_||!_.length)throw new Error("bad png - invalid inflate data response");let w=B_.process(_,s);h=null;let E=U_.dataToBitMap(w,s);w=null;let L=q_(E,s);return s.data=L,s.gamma=c||0,s}});var zu=v((kI,Vu)=>{"use strict";var Gu=!0,ju=require("zlib");ju.deflateSync||(Gu=!1);var $_=tn(),W_=so();Vu.exports=function(t,e){if(!Gu)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},r=new W_(n),s=[];s.push(Buffer.from($_.PNG_SIGNATURE)),s.push(r.packIHDR(t.width,t.height)),t.gamma&&s.push(r.packGAMA(t.gamma));let i=r.filterData(t.data,t.width,t.height),o=ju.deflateSync(i,r.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return s.push(r.packIDAT(o)),s.push(r.packIEND()),Buffer.concat(s)}});var Yu=v(oo=>{"use strict";var G_=Wu(),j_=zu();oo.read=function(t,e){return G_(t,e||{})};oo.write=function(t,e){return j_(t,e)}});var Qu=v(Ju=>{"use strict";var V_=require("util"),Ku=require("stream"),z_=Su(),Y_=Ru(),K_=Yu(),me=Ju.PNG=function(t){Ku.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 z_(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 Y_(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"))};V_.inherits(me,Ku);me.sync=K_;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 n,r;n=function(s){this.removeListener("error",r),this.data=s,e(null,this)}.bind(this),r=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",r)}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,n,r,s,i,o,a){if(n|=0,r|=0,s|=0,i|=0,o|=0,a|=0,n>t.width||r>t.height||n+s>t.width||r+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+s>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(r+l)*t.width+n<<2,(r+l)*t.width+n+s<<2)};me.prototype.bitblt=function(t,e,n,r,s,i,o){return me.bitblt(this,t,e,n,r,s,i,o),this};me.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let s=0;s<3;s++){let i=t.data[r+s]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[r+s]=Math.round(i*255)}}t.gamma=0}};me.prototype.adjustGamma=function(){me.adjustGamma(this)}});var $n=v(Rt=>{function Xu(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(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}Rt.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:n,color:{dark:Xu(e.color.dark||"#000000ff"),light:Xu(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Rt.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};Rt.getImageWidth=function(e,n){let r=Rt.getScale(e,n);return Math.floor((e+n.margin*2)*r)};Rt.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=Rt.getScale(s,r),a=Math.floor((s+r.margin*2)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let u=0;u<a;u++)for(let d=0;d<a;d++){let f=(u*a+d)*4,p=r.color.light;if(u>=l&&d>=l&&u<a-l&&d<a-l){let g=Math.floor((u-l)/o),h=Math.floor((d-l)/o);p=c[i[g*s+h]?1:0]}e[f++]=p.r,e[f++]=p.g,e[f++]=p.b,e[f]=p.a}}});var Zu=v(Ge=>{var J_=require("fs"),Q_=Qu().PNG,ao=$n();Ge.render=function(e,n){let r=ao.getOptions(n),s=r.rendererOpts,i=ao.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new Q_(s);return ao.qrToImageData(o.data,e,r),o};Ge.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),Ge.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};Ge.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=Ge.render(e,n),i=[];s.on("error",r),s.on("data",function(o){i.push(o)}),s.on("end",function(){r(null,Buffer.concat(i))}),s.pack()};Ge.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=!1,o=(...l)=>{i||(i=!0,s.apply(null,l))},a=J_.createWriteStream(e);a.on("error",o),a.on("close",o),Ge.renderToFileStream(a,n,r)};Ge.renderToFileStream=function(e,n,r){Ge.render(n,r).pack().pipe(e)}});var ed=v(Jr=>{var X_=$n(),Z_={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},eS={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function tS(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Jr.render=function(t,e,n){let r=X_.getOptions(e),s=Z_;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=eS);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+r.margin*2+1).join(s.WW);l=Array(r.margin/2+1).join(l+`
14
- `);let c=Array(r.margin+1).join(s.WW);a+=l;for(let u=0;u<i;u+=2){a+=c;for(let d=0;d<i;d++){let f=o[u*i+d],p=o[(u+1)*i+d];a+=tS(f,p,s)}a+=c+`
15
- `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};Jr.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),o=Jr.render(n,r);i.writeFile(e,o,s)}});var nd=v(td=>{td.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(r+3).join(o),c=Array(2).join(o);a+=l+`
13
+ `);let o=Tp(e,n,s),a=zn.getSymbolSize(e),l=new hp(a);return _p(l,e),bp(l),wp(l,e),Ss(l,n,0),e>=7&&Ip(l,e),Ap(l,o),isNaN(r)&&(r=_s.getBestMask(l,Ss.bind(null,l,n))),_s.applyMask(r,l),Ss(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}Ba.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=ys.M,s,i;return typeof n<"u"&&(r=ys.from(n.errorCorrectionLevel,ys.M),s=$n.from(n.version),i=_s.from(n.maskPattern),n.toSJISFunc&&zn.setToSJISFunction(n.toSJISFunc)),Cp(e,s,r,i)}});var Is=y((Hv,Ha)=>{"use strict";var kp=require("util"),Da=require("stream"),ie=Ha.exports=function(){Da.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};kp.inherits(ie,Da);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 n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.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,n=0,r=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],i=Math.min(s.length,t.length-e);s.copy(r,e,0,i),e+=i,i!==s.length&&(this._buffers[--n]=s.slice(i))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,r)};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 Ts=y(As=>{"use strict";var Ee=[{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]}];As.getImagePasses=function(t,e){let n=[],r=t%8,s=e%8,i=(t-r)/8,o=(e-s)/8;for(let a=0;a<Ee.length;a++){let l=Ee[a],c=i*l.x.length,u=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<r;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};As.getInterlaceIterator=function(t){return function(e,n,r){let s=e%Ee[r].x.length,i=(e-s)/Ee[r].x.length*8+Ee[r].x[s],o=n%Ee[r].y.length,a=(n-o)/Ee[r].y.length*8+Ee[r].y[o];return i*4+a*t*4}}});var xs=y((Uv,Fa)=>{"use strict";Fa.exports=function(e,n,r){let s=e+n-r,i=Math.abs(s-e),o=Math.abs(s-n),a=Math.abs(s-r);return i<=o&&i<=a?e:o<=a?n:r}});var Cs=y((qv,qa)=>{"use strict";var Ep=Ts(),Pp=xs();function Ua(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var mt=qa.exports=function(t,e){let n=t.width,r=t.height,s=t.interlace,i=t.bpp,o=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=Ep.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Ua(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Ua(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};mt.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};mt.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,s=r-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>s?e[i-r]:0;e[i]=o+a}};mt.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let s=0;s<n;s++){let i=t[1+s],o=r?r[s]:0;e[s]=i+o}};mt.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=Math.floor((c+l)/2);e[o]=a+u}};mt.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=o>s&&i?i[o-r]:0,d=Pp(c,l,u);e[o]=a+d}};mt.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],s=r.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var ja=y((Wv,Ga)=>{"use strict";var Rp=require("util"),Wa=Is(),Mp=Cs(),Lp=Ga.exports=function(t){Wa.call(this);let e=[],n=this;this._filter=new Mp(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Rp.inherits(Lp,Wa)});var yt=y((Gv,Va)=>{"use strict";Va.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 Ps=y((jv,$a)=>{"use strict";var ks=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;ks[t]=e}})();var Es=$a.exports=function(){this._crc=-1};Es.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=ks[(this._crc^t[e])&255]^this._crc>>>8;return!0};Es.prototype.crc32=function(){return this._crc^-1};Es.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=ks[(e^t[n])&255]^e>>>8;return e^-1}});var Rs=y((Vv,za)=>{"use strict";var B=yt(),Np=Ps(),U=za.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[B.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[B.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[B.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[B.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[B.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[B.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(){}};U.prototype.start=function(){this.read(B.PNG_SIGNATURE.length,this._parseSignature.bind(this))};U.prototype._parseSignature=function(t){let e=B.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};U.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r="";for(let i=4;i<8;i++)r+=String.fromCharCode(t[i]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==B.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Np,this._crc.write(Buffer.from(r)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+r));return}this.read(e+4,this._skipChunk.bind(this))};U.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};U.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};U.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};U.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};U.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),r=t[8],s=t[9],i=t[10],o=t[11],a=t[12];if(r!==8&&r!==4&&r!==2&&r!==1&&r!==16){this.error(new Error("Unsupported bit depth "+r));return}if(!(s in B.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(o!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let l=B.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&B.COLORTYPE_PALETTE),color:!!(s&B.COLORTYPE_COLOR),alpha:!!(s&B.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};U.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};U.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};U.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};U.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===B.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===B.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===B.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};U.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};U.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/B.GAMMA_DIVISION),this._handleChunkEnd()};U.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};U.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===B.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};U.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};U.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Ms=y(Ja=>{"use strict";var Ya=Ts(),Op=[function(){},function(t,e,n,r){if(r===e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,r){if(r+1>=e.length)throw new Error("Ran out of data");let s=e[r];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[r+1]},function(t,e,n,r){if(r+2>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=255},function(t,e,n,r){if(r+3>=e.length)throw new Error("Ran out of data");t[n]=e[r],t[n+1]=e[r+1],t[n+2]=e[r+2],t[n+3]=e[r+3]}],Bp=[function(){},function(t,e,n,r){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=r},function(t,e,n){let r=e[0];t[n]=r,t[n+1]=r,t[n+2]=r,t[n+3]=e[1]},function(t,e,n,r){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=r},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function Dp(t,e){let n=[],r=0;function s(){if(r===t.length)throw new Error("Ran out of data");let i=t[r];r++;let o,a,l,c,u,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[r],r++,n.push((i<<8)+f);break;case 4:f=i&15,h=i>>4,n.push(h,f);break;case 2:u=i&3,d=i>>2&3,f=i>>4&3,h=i>>6&3,n.push(h,f,d,u);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,c=i>>3&1,u=i>>4&1,d=i>>5&1,f=i>>6&1,h=i>>7&1,n.push(h,f,d,u,c,l,a,o);break}}return{get:function(i){for(;n.length<i;)s();let o=n.slice(0,i);return n=n.slice(i),o},resetAfterLine:function(){n.length=0},end:function(){if(r!==t.length)throw new Error("extra data found")}}}function Hp(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++)for(let u=0;u<o;u++){let d=n(u,c,l);Op[r](e,s,d,i),i+=r}return i}function Fp(t,e,n,r,s,i){let o=t.width,a=t.height,l=t.index;for(let c=0;c<a;c++){for(let u=0;u<o;u++){let d=s.get(r),f=n(u,c,l);Bp[r](e,d,f,i)}s.resetAfterLine()}}Ja.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=Dp(t,s));let l;s<=8?l=Buffer.alloc(n*r*4):l=new Uint16Array(n*r*4);let c=Math.pow(2,s)-1,u=0,d,f;if(o)d=Ya.getImagePasses(n,r),f=Ya.getInterlaceIterator(n,r);else{let h=0;f=function(){let g=h;return h+=4,g},d=[{width:n,height:r}]}for(let h=0;h<d.length;h++)s===8?u=Hp(d[h],l,f,i,t,u):Fp(d[h],l,f,i,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var Ls=y((zv,Ka)=>{"use strict";function Up(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=s[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let c=0;c<4;c++)e[i+c]=l[c];i+=4}}function qp(t,e,n,r,s){let i=0;for(let o=0;o<r;o++)for(let a=0;a<n;a++){let l=!1;if(s.length===1?s[0]===t[i]&&(l=!0):s[0]===t[i]&&s[1]===t[i+1]&&s[2]===t[i+2]&&(l=!0),l)for(let c=0;c<4;c++)e[i+c]=0;i+=4}}function Wp(t,e,n,r,s){let i=255,o=Math.pow(2,s)-1,a=0;for(let l=0;l<r;l++)for(let c=0;c<n;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*i/o+.5);a+=4}}Ka.exports=function(t,e){let n=e.depth,r=e.width,s=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?Up(t,l,r,s,a):(o&&qp(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),Wp(t,l,r,s,n))),l}});var Za=y((Yv,Xa)=>{"use strict";var Gp=require("util"),Ns=require("zlib"),Qa=Is(),jp=ja(),Vp=Rs(),$p=Ms(),zp=Ls(),fe=Xa.exports=function(t){Qa.call(this),this._parser=new Vp(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()};Gp.inherits(fe,Qa);fe.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};fe.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Ns.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 n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,r=Math.max(n,Ns.Z_MIN_CHUNK);this._inflate=Ns.createInflate({chunkSize:r});let s=n,i=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&i(a)}),this._filter.on("complete",this._complete.bind(this));let o=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,o(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};fe.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new jp(this._bitmapInfo)};fe.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};fe.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};fe.prototype._simpleTransparency=function(){this._metaData.alpha=!0};fe.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};fe.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};fe.prototype._complete=function(t){if(this.errord)return;let e;try{let n=$p.dataToBitMap(t,this._bitmapInfo);e=zp(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var tl=y((Jv,el)=>{"use strict";var te=yt();el.exports=function(t,e,n,r){let s=[te.COLORTYPE_COLOR_ALPHA,te.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let g=(function(){let p=new ArrayBuffer(2);return new DataView(p).setInt16(0,256,!0),new Int16Array(p)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&g)return t}let i=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=te.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=te.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,d=0,f=r.bgColor||{};f.red===void 0&&(f.red=o),f.green===void 0&&(f.green=o),f.blue===void 0&&(f.blue=o);function h(){let g,p,m,v=o;switch(r.inputColorType){case te.COLORTYPE_COLOR_ALPHA:v=i[u+3],g=i[u],p=i[u+1],m=i[u+2];break;case te.COLORTYPE_COLOR:g=i[u],p=i[u+1],m=i[u+2];break;case te.COLORTYPE_ALPHA:v=i[u+1],g=i[u],p=g,m=g;break;case te.COLORTYPE_GRAYSCALE:g=i[u],p=g,m=g;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(v/=o,g=Math.min(Math.max(Math.round((1-v)*f.red+v*g),0),o),p=Math.min(Math.max(Math.round((1-v)*f.green+v*p),0),o),m=Math.min(Math.max(Math.round((1-v)*f.blue+v*m),0),o))),{red:g,green:p,blue:m,alpha:v}}for(let g=0;g<n;g++)for(let p=0;p<e;p++){let m=h(i,u);switch(r.colorType){case te.COLORTYPE_COLOR_ALPHA:case te.COLORTYPE_COLOR:r.bitDepth===8?(c[d]=m.red,c[d+1]=m.green,c[d+2]=m.blue,s&&(c[d+3]=m.alpha)):(c.writeUInt16BE(m.red,d),c.writeUInt16BE(m.green,d+2),c.writeUInt16BE(m.blue,d+4),s&&c.writeUInt16BE(m.alpha,d+6));break;case te.COLORTYPE_ALPHA:case te.COLORTYPE_GRAYSCALE:{let v=(m.red+m.green+m.blue)/3;r.bitDepth===8?(c[d]=v,s&&(c[d+1]=m.alpha)):(c.writeUInt16BE(v,d),s&&c.writeUInt16BE(m.alpha,d+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,d+=l}return c}});var sl=y((Kv,rl)=>{"use strict";var nl=xs();function Yp(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function Jp(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function Kp(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;r[s+o]=l}}function Qp(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=t[e+i]-o;s+=Math.abs(a)}return s}function Xp(t,e,n,r,s){for(let i=0;i<n;i++){let o=e>0?t[e+i-n]:0,a=t[e+i]-o;r[s+i]=a}}function Zp(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++){let o=e>0?t[i-n]:0,a=t[i]-o;r+=Math.abs(a)}return r}function eh(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=t[e+o]-(a+l>>1);r[s+o]=c}}function th(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function nh(t,e,n,r,s,i){for(let o=0;o<n;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-n]:0,c=e>0&&o>=i?t[e+o-(n+i)]:0,u=t[e+o]-nl(a,l,c);r[s+o]=u}}function rh(t,e,n,r){let s=0;for(let i=0;i<n;i++){let o=i>=r?t[e+i-r]:0,a=e>0?t[e+i-n]:0,l=e>0&&i>=r?t[e+i-(n+r)]:0,c=t[e+i]-nl(o,a,l);s+=Math.abs(c)}return s}var sh={0:Yp,1:Kp,2:Xp,3:eh,4:nh},ih={0:Jp,1:Qp,2:Zp,3:th,4:rh};rl.exports=function(t,e,n,r,s){let i;if(!("filterType"in r)||r.filterType===-1)i=[0,1,2,3,4];else if(typeof r.filterType=="number")i=[r.filterType];else throw new Error("unrecognised filter types");r.bitDepth===16&&(s*=2);let o=e*s,a=0,l=0,c=Buffer.alloc((o+1)*n),u=i[0];for(let d=0;d<n;d++){if(i.length>1){let f=1/0;for(let h=0;h<i.length;h++){let g=ih[i[h]](t,l,o,s);g<f&&(u=i[h],f=g)}}c[a]=u,a++,sh[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var Os=y((Qv,il)=>{"use strict";var W=yt(),oh=Ps(),ah=tl(),lh=sl(),ch=require("zlib"),Pe=il.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||ch.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:W.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:W.COLORTYPE_COLOR_ALPHA,[W.COLORTYPE_GRAYSCALE,W.COLORTYPE_COLOR,W.COLORTYPE_COLOR_ALPHA,W.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([W.COLORTYPE_GRAYSCALE,W.COLORTYPE_COLOR,W.COLORTYPE_COLOR_ALPHA,W.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")};Pe.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Pe.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Pe.prototype.filterData=function(t,e,n){let r=ah(t,e,n,this._options),s=W.COLORTYPE_TO_BPP_MAP[this._options.colorType];return lh(r,e,n,this._options,s)};Pe.prototype._packChunk=function(t,e){let n=e?e.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(t,4),e&&e.copy(r,8),r.writeInt32BE(oh.crc32(r.slice(4,r.length-4)),r.length-4),r};Pe.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*W.GAMMA_DIVISION),0),this._packChunk(W.TYPE_gAMA,e)};Pe.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(W.TYPE_IHDR,n)};Pe.prototype.packIDAT=function(t){return this._packChunk(W.TYPE_IDAT,t)};Pe.prototype.packIEND=function(){return this._packChunk(W.TYPE_IEND,null)}});var cl=y((Xv,ll)=>{"use strict";var uh=require("util"),ol=require("stream"),dh=yt(),fh=Os(),al=ll.exports=function(t){ol.call(this);let e=t||{};this._packer=new fh(e),this._deflate=this._packer.createDeflate(),this.readable=!0};uh.inherits(al,ol);al.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(dh.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),r&&this.emit("data",this._packer.packGAMA(r));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var gl=y((Qt,hl)=>{"use strict";var ul=require("assert").ok,vt=require("zlib"),ph=require("util"),dl=require("buffer").kMaxLength;function $e(t){if(!(this instanceof $e))return new $e(t);t&&t.chunkSize<vt.Z_MIN_CHUNK&&(t.chunkSize=vt.Z_MIN_CHUNK),vt.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 hh(t){return new $e(t)}function fl(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}$e.prototype._processChunk=function(t,e,n){if(typeof n=="function")return vt.Inflate._processChunk.call(this,t,e,n);let r=this,s=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(g){u=g});function d(g,p){if(r._hadError)return;let m=i-p;if(ul(m>=0,"have should not go down"),m>0){let v=r._buffer.slice(r._offset,r._offset+m);if(r._offset+=m,v.length>o&&(v=v.slice(0,o)),l.push(v),c+=v.length,o-=v.length,o===0)return!1}return(p===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),p===0?(a+=s-g,s=g,!0):!1}ul(this._handle,"zlib binding closed");let f;do f=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),f=f||this._writeState;while(!this._hadError&&d(f[0],f[1]));if(this._hadError)throw u;if(c>=dl)throw fl(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+dl.toString(16)+" bytes");let h=Buffer.concat(l,c);return fl(this),h};ph.inherits($e,vt.Inflate);function gh(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=vt.Z_FINISH),t._processChunk(e,n)}function pl(t,e){return gh(new $e(e),t)}hl.exports=Qt=pl;Qt.Inflate=$e;Qt.createInflate=hh;Qt.inflateSync=pl});var Bs=y((Zv,yl)=>{"use strict";var ml=yl.exports=function(t){this._buffer=t,this._reads=[]};ml.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};ml.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 Sl=y(vl=>{"use strict";var mh=Bs(),yh=Cs();vl.process=function(t,e){let n=[],r=new mh(t);return new yh(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Il=y((tS,wl)=>{"use strict";var _l=!0,bl=require("zlib"),vh=gl();bl.deflateSync||(_l=!1);var Sh=Bs(),_h=Sl(),bh=Rs(),wh=Ms(),Ih=Ls();wl.exports=function(t,e){if(!_l)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function r(C){n=C}let s;function i(C){s=C}function o(C){s.transColor=C}function a(C){s.palette=C}function l(){s.alpha=!0}let c;function u(C){c=C}let d=[];function f(C){d.push(C)}let h=new Sh(t);if(new bh(e,{read:h.read.bind(h),error:r,metadata:i,gamma:u,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),h.process(),n)throw n;let p=Buffer.concat(d);d.length=0;let m;if(s.interlace)m=bl.inflateSync(p);else{let H=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;m=vh(p,{chunkSize:H,maxLength:H})}if(p=null,!m||!m.length)throw new Error("bad png - invalid inflate data response");let v=_h.process(m,s);p=null;let b=wh.dataToBitMap(v,s);v=null;let K=Ih(b,s);return s.data=K,s.gamma=c||0,s}});var Cl=y((nS,xl)=>{"use strict";var Al=!0,Tl=require("zlib");Tl.deflateSync||(Al=!1);var Ah=yt(),Th=Os();xl.exports=function(t,e){if(!Al)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},r=new Th(n),s=[];s.push(Buffer.from(Ah.PNG_SIGNATURE)),s.push(r.packIHDR(t.width,t.height)),t.gamma&&s.push(r.packGAMA(t.gamma));let i=r.filterData(t.data,t.width,t.height),o=Tl.deflateSync(i,r.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return s.push(r.packIDAT(o)),s.push(r.packIEND()),Buffer.concat(s)}});var kl=y(Ds=>{"use strict";var xh=Il(),Ch=Cl();Ds.read=function(t,e){return xh(t,e||{})};Ds.write=function(t,e){return Ch(t,e)}});var Rl=y(Pl=>{"use strict";var kh=require("util"),El=require("stream"),Eh=Za(),Ph=cl(),Rh=kl(),j=Pl.PNG=function(t){El.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 Eh(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 Ph(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"))};kh.inherits(j,El);j.sync=Rh;j.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)};j.prototype.parse=function(t,e){if(e){let n,r;n=function(s){this.removeListener("error",r),this.data=s,e(null,this)}.bind(this),r=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",r)}return this.end(t),this};j.prototype.write=function(t){return this._parser.write(t),!0};j.prototype.end=function(t){this._parser.end(t)};j.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};j.prototype._gamma=function(t){this.gamma=t};j.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};j.bitblt=function(t,e,n,r,s,i,o,a){if(n|=0,r|=0,s|=0,i|=0,o|=0,a|=0,n>t.width||r>t.height||n+s>t.width||r+i>t.height)throw new Error("bitblt reading outside image");if(o>e.width||a>e.height||o+s>e.width||a+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(a+l)*e.width+o<<2,(r+l)*t.width+n<<2,(r+l)*t.width+n+s<<2)};j.prototype.bitblt=function(t,e,n,r,s,i,o){return j.bitblt(this,t,e,n,r,s,i,o),this};j.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let r=t.width*e+n<<2;for(let s=0;s<3;s++){let i=t.data[r+s]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[r+s]=Math.round(i*255)}}t.gamma=0}};j.prototype.adjustGamma=function(){j.adjustGamma(this)}});var Xt=y(ze=>{function Ml(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(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}ze.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:n,color:{dark:Ml(e.color.dark||"#000000ff"),light:Ml(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};ze.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};ze.getImageWidth=function(e,n){let r=ze.getScale(e,n);return Math.floor((e+n.margin*2)*r)};ze.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=ze.getScale(s,r),a=Math.floor((s+r.margin*2)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let u=0;u<a;u++)for(let d=0;d<a;d++){let f=(u*a+d)*4,h=r.color.light;if(u>=l&&d>=l&&u<a-l&&d<a-l){let g=Math.floor((u-l)/o),p=Math.floor((d-l)/o);h=c[i[g*s+p]?1:0]}e[f++]=h.r,e[f++]=h.g,e[f++]=h.b,e[f]=h.a}}});var Ll=y(pe=>{var Mh=require("fs"),Lh=Rl().PNG,Hs=Xt();pe.render=function(e,n){let r=Hs.getOptions(n),s=r.rendererOpts,i=Hs.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new Lh(s);return Hs.qrToImageData(o.data,e,r),o};pe.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),pe.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};pe.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=pe.render(e,n),i=[];s.on("error",r),s.on("data",function(o){i.push(o)}),s.on("end",function(){r(null,Buffer.concat(i))}),s.pack()};pe.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=!1,o=(...l)=>{i||(i=!0,s.apply(null,l))},a=Mh.createWriteStream(e);a.on("error",o),a.on("close",o),pe.renderToFileStream(a,n,r)};pe.renderToFileStream=function(e,n,r){pe.render(n,r).pack().pipe(e)}});var Nl=y(Yn=>{var Nh=Xt(),Oh={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Bh={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Dh(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Yn.render=function(t,e,n){let r=Nh.getOptions(e),s=Oh;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=Bh);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+r.margin*2+1).join(s.WW);l=Array(r.margin/2+1).join(l+`
14
+ `);let c=Array(r.margin+1).join(s.WW);a+=l;for(let u=0;u<i;u+=2){a+=c;for(let d=0;d<i;d++){let f=o[u*i+d],h=o[(u+1)*i+d];a+=Dh(f,h,s)}a+=c+`
15
+ `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};Yn.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),o=Yn.render(n,r);i.writeFile(e,o,s)}});var Bl=y(Ol=>{Ol.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(r+3).join(o),c=Array(2).join(o);a+=l+`
16
16
  `;for(let u=0;u<r;++u){a+=o;for(let d=0;d<r;d++)a+=s[u*r+d]?i:o;a+=c+`
17
17
  `}return a+=l+`
18
- `,typeof n=="function"&&n(null,a),a}});var od=v(id=>{var nS="\x1B[47m",rS="\x1B[40m",lo="\x1B[37m",co="\x1B[30m",kt="\x1B[0m",sS=nS+co,iS=rS+lo,oS=function(t,e,n){return{"00":kt+" "+t,"01":kt+e+"\u2584"+t,"02":kt+n+"\u2584"+t,10:kt+e+"\u2580"+t,11:" ",12:"\u2584",20:kt+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},rd=function(t,e,n,r){let s=e+1;if(n>=s||r>=s||r<-1||n<-1)return"0";if(n>=e||r>=e||r<0||n<0)return"1";let i=r*e+n;return t[i]?"2":"1"},sd=function(t,e,n,r){return rd(t,e,n,r)+rd(t,e,n,r+1)};id.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?iS:sS,c=oS(o,i?co:lo,i?lo:co),u=kt+`
19
- `+o,d=o;for(let f=-1;f<r+1;f+=2){for(let p=-1;p<r;p++)d+=c[sd(s,r,p,f)];d+=c[sd(s,r,r,f)]+u}return d+=kt,typeof n=="function"&&n(null,d),d}});var ld=v(ad=>{var aS=nd(),lS=od();ad.render=function(t,e,n){return e&&e.small?lS.render(t,e,n):aS.render(t,e,n)}});var fo=v(ud=>{var cS=$n();function cd(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function uo(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function uS(t,e,n){let r="",s=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),c=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(r+=i?uo("M",l+n,.5+c+n):uo("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=uo("h",o),o=0)):s++}return r}ud.render=function(e,n,r){let s=cS.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+cd(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+cd(s.color.dark,"stroke")+' d="'+uS(o,i,s.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
20
- `;return typeof r=="function"&&r(null,f),f}});var dd=v(Qr=>{var dS=fo();Qr.render=dS.render;Qr.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),a='<?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">'+Qr.render(n,r);i.writeFile(e,a,s)}});var fd=v(Xr=>{var ho=$n();function fS(t,e,n){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=n,e.width=n,e.style.height=n+"px",e.style.width=n+"px"}function hS(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Xr.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=hS()),s=ho.getOptions(s);let o=ho.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return ho.qrToImageData(l.data,e,s),fS(a,i,o),a.putImageData(l,0,0),i};Xr.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=Xr.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var pd=v(Wn=>{var pS=xi(),po=ji(),hd=fd(),gS=fo();function go(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!pS())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=n,n=e,e=r=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=r=void 0):o===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(l,c){try{let u=po.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=po.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}Wn.create=po.create;Wn.toCanvas=go.bind(null,hd.render);Wn.toDataURL=go.bind(null,hd.renderToDataURL);Wn.toString=go.bind(null,function(t,e,n){return gS.render(t,n)})});var _d=v(ft=>{var gd=xi(),mo=ji(),mS=Zu(),md=ed(),yS=ld(),yd=dd();function Gn(t,e,n){if(typeof t>"u")throw new Error("String required as first argument");if(typeof n>"u"&&(n=e,e={}),typeof n!="function")if(gd())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function _S(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Zr(t){switch(t){case"svg":return yd;case"txt":case"utf8":return md;case"png":case"image/png":default:return mS}}function SS(t){switch(t){case"svg":return yd;case"terminal":return yS;case"utf8":default:return md}}function jn(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=mo.create(e,n.opts);return t(i,n.opts,function(o,a){return o?s(o):r(a)})}catch(i){s(i)}});try{let r=mo.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}ft.create=mo.create;ft.toCanvas=pd().toCanvas;ft.toString=function(e,n,r){let s=Gn(e,n,r),i=s.opts?s.opts.type:void 0,o=SS(i);return jn(o.render,e,s)};ft.toDataURL=function(e,n,r){let s=Gn(e,n,r),i=Zr(s.opts.type);return jn(i.renderToDataURL,e,s)};ft.toBuffer=function(e,n,r){let s=Gn(e,n,r),i=Zr(s.opts.type);return jn(i.renderToBuffer,e,s)};ft.toFile=function(e,n,r,s){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!gd())throw new Error("Too few arguments provided");let i=Gn(n,r,s),o=i.opts.type||_S(e),l=Zr(o).renderToFile.bind(null,e);return jn(l,n,i)};ft.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=Gn(n,r,e.emit.bind(e,"error")),o=Zr("png").renderToFileStream.bind(null,e);jn(o,n,s)}});var vd=v((GI,Sd)=>{Sd.exports=_d()});var Zn=v((Ax,mf)=>{"use strict";var Tv=require("path"),je="\\\\/",ff=`[^${je}]`,Ze="\\.",Rv="\\+",kv="\\?",hs="\\/",Pv="(?=.)",hf="[^/]",No=`(?:${hs}|$)`,pf=`(?:^|${hs})`,Oo=`${Ze}{1,2}${No}`,Mv=`(?!${Ze})`,Lv=`(?!${pf}${Oo})`,Nv=`(?!${Ze}{0,1}${No})`,Ov=`(?!${Oo})`,Dv=`[^.${hs}]`,Hv=`${hf}*?`,gf={DOT_LITERAL:Ze,PLUS_LITERAL:Rv,QMARK_LITERAL:kv,SLASH_LITERAL:hs,ONE_CHAR:Pv,QMARK:hf,END_ANCHOR:No,DOTS_SLASH:Oo,NO_DOT:Mv,NO_DOTS:Lv,NO_DOT_SLASH:Nv,NO_DOTS_SLASH:Ov,QMARK_NO_DOT:Dv,STAR:Hv,START_ANCHOR:pf},Bv={...gf,SLASH_LITERAL:`[${je}]`,QMARK:ff,STAR:`${ff}*?`,DOTS_SLASH:`${Ze}{1,2}(?:[${je}]|$)`,NO_DOT:`(?!${Ze})`,NO_DOTS:`(?!(?:^|[${je}])${Ze}{1,2}(?:[${je}]|$))`,NO_DOT_SLASH:`(?!${Ze}{0,1}(?:[${je}]|$))`,NO_DOTS_SLASH:`(?!${Ze}{1,2}(?:[${je}]|$))`,QMARK_NO_DOT:`[^.${je}]`,START_ANCHOR:`(?:^|[${je}])`,END_ANCHOR:`(?:[${je}]|$)`},Fv={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};mf.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Fv,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:Tv.sep,extglobChars(t){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${t.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(t){return t===!0?Bv:gf}}});var ps=v(Se=>{"use strict";var Uv=require("path"),qv=process.platform==="win32",{REGEX_BACKSLASH:$v,REGEX_REMOVE_BACKSLASH:Wv,REGEX_SPECIAL_CHARS:Gv,REGEX_SPECIAL_CHARS_GLOBAL:jv}=Zn();Se.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);Se.hasRegexChars=t=>Gv.test(t);Se.isRegexChar=t=>t.length===1&&Se.hasRegexChars(t);Se.escapeRegex=t=>t.replace(jv,"\\$1");Se.toPosixSlashes=t=>t.replace($v,"/");Se.removeBackslashes=t=>t.replace(Wv,e=>e==="\\"?"":e);Se.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};Se.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:qv===!0||Uv.sep==="\\";Se.escapeLast=(t,e,n)=>{let r=t.lastIndexOf(e,n);return r===-1?t:t[r-1]==="\\"?Se.escapeLast(t,e,r-1):`${t.slice(0,r)}\\${t.slice(r)}`};Se.removePrefix=(t,e={})=>{let n=t;return n.startsWith("./")&&(n=n.slice(2),e.prefix="./"),n};Se.wrapOutput=(t,e={},n={})=>{let r=n.contains?"":"^",s=n.contains?"":"$",i=`${r}(?:${t})${s}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var Ef=v((Ix,Af)=>{"use strict";var yf=ps(),{CHAR_ASTERISK:Do,CHAR_AT:Vv,CHAR_BACKWARD_SLASH:er,CHAR_COMMA:zv,CHAR_DOT:Ho,CHAR_EXCLAMATION_MARK:Bo,CHAR_FORWARD_SLASH:bf,CHAR_LEFT_CURLY_BRACE:Fo,CHAR_LEFT_PARENTHESES:Uo,CHAR_LEFT_SQUARE_BRACKET:Yv,CHAR_PLUS:Kv,CHAR_QUESTION_MARK:_f,CHAR_RIGHT_CURLY_BRACE:Jv,CHAR_RIGHT_PARENTHESES:Sf,CHAR_RIGHT_SQUARE_BRACKET:Qv}=Zn(),vf=t=>t===bf||t===er,wf=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},Xv=(t,e)=>{let n=e||{},r=t.length-1,s=n.parts===!0||n.scanToEnd===!0,i=[],o=[],a=[],l=t,c=-1,u=0,d=0,f=!1,p=!1,g=!1,h=!1,_=!1,w=!1,E=!1,L=!1,N=!1,O=!1,X=0,U,x,D={value:"",depth:0,isGlob:!1},re=()=>c>=r,S=()=>l.charCodeAt(c+1),j=()=>(U=x,l.charCodeAt(++c));for(;c<r;){x=j();let pe;if(x===er){E=D.backslashes=!0,x=j(),x===Fo&&(w=!0);continue}if(w===!0||x===Fo){for(X++;re()!==!0&&(x=j());){if(x===er){E=D.backslashes=!0,j();continue}if(x===Fo){X++;continue}if(w!==!0&&x===Ho&&(x=j())===Ho){if(f=D.isBrace=!0,g=D.isGlob=!0,O=!0,s===!0)continue;break}if(w!==!0&&x===zv){if(f=D.isBrace=!0,g=D.isGlob=!0,O=!0,s===!0)continue;break}if(x===Jv&&(X--,X===0)){w=!1,f=D.isBrace=!0,O=!0;break}}if(s===!0)continue;break}if(x===bf){if(i.push(c),o.push(D),D={value:"",depth:0,isGlob:!1},O===!0)continue;if(U===Ho&&c===u+1){u+=2;continue}d=c+1;continue}if(n.noext!==!0&&(x===Kv||x===Vv||x===Do||x===_f||x===Bo)===!0&&S()===Uo){if(g=D.isGlob=!0,h=D.isExtglob=!0,O=!0,x===Bo&&c===u&&(N=!0),s===!0){for(;re()!==!0&&(x=j());){if(x===er){E=D.backslashes=!0,x=j();continue}if(x===Sf){g=D.isGlob=!0,O=!0;break}}continue}break}if(x===Do){if(U===Do&&(_=D.isGlobstar=!0),g=D.isGlob=!0,O=!0,s===!0)continue;break}if(x===_f){if(g=D.isGlob=!0,O=!0,s===!0)continue;break}if(x===Yv){for(;re()!==!0&&(pe=j());){if(pe===er){E=D.backslashes=!0,j();continue}if(pe===Qv){p=D.isBracket=!0,g=D.isGlob=!0,O=!0;break}}if(s===!0)continue;break}if(n.nonegate!==!0&&x===Bo&&c===u){L=D.negated=!0,u++;continue}if(n.noparen!==!0&&x===Uo){if(g=D.isGlob=!0,s===!0){for(;re()!==!0&&(x=j());){if(x===Uo){E=D.backslashes=!0,x=j();continue}if(x===Sf){O=!0;break}}continue}break}if(g===!0){if(O=!0,s===!0)continue;break}}n.noext===!0&&(h=!1,g=!1);let W=l,rt="",m="";u>0&&(rt=l.slice(0,u),l=l.slice(u),d-=u),W&&g===!0&&d>0?(W=l.slice(0,d),m=l.slice(d)):g===!0?(W="",m=l):W=l,W&&W!==""&&W!=="/"&&W!==l&&vf(W.charCodeAt(W.length-1))&&(W=W.slice(0,-1)),n.unescape===!0&&(m&&(m=yf.removeBackslashes(m)),W&&E===!0&&(W=yf.removeBackslashes(W)));let y={prefix:rt,input:t,start:u,base:W,glob:m,isBrace:f,isBracket:p,isGlob:g,isExtglob:h,isGlobstar:_,negated:L,negatedExtglob:N};if(n.tokens===!0&&(y.maxDepth=0,vf(x)||o.push(D),y.tokens=o),n.parts===!0||n.tokens===!0){let pe;for(let H=0;H<i.length;H++){let Ue=pe?pe+1:u,qe=i[H],we=t.slice(Ue,qe);n.tokens&&(H===0&&u!==0?(o[H].isPrefix=!0,o[H].value=rt):o[H].value=we,wf(o[H]),y.maxDepth+=o[H].depth),(H!==0||we!=="")&&a.push(we),pe=qe}if(pe&&pe+1<t.length){let H=t.slice(pe+1);a.push(H),n.tokens&&(o[o.length-1].value=H,wf(o[o.length-1]),y.maxDepth+=o[o.length-1].depth)}y.slashes=i,y.parts=a}return y};Af.exports=Xv});var Cf=v((xx,xf)=>{"use strict";var gs=Zn(),Ae=ps(),{MAX_LENGTH:ms,POSIX_REGEX_SOURCE:Zv,REGEX_NON_SPECIAL_CHARS:ew,REGEX_SPECIAL_CHARS_BACKREF:tw,REPLACEMENTS:If}=gs,nw=(t,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...t,e);t.sort();let n=`[${t.join("-")}]`;try{new RegExp(n)}catch{return t.map(s=>Ae.escapeRegex(s)).join("..")}return n},cn=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,qo=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=If[t]||t;let n={...e},r=typeof n.maxLength=="number"?Math.min(ms,n.maxLength):ms,s=t.length;if(s>r)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${r}`);let i={type:"bos",value:"",output:n.prepend||""},o=[i],a=n.capture?"":"?:",l=Ae.isWindows(e),c=gs.globChars(l),u=gs.extglobChars(c),{DOT_LITERAL:d,PLUS_LITERAL:f,SLASH_LITERAL:p,ONE_CHAR:g,DOTS_SLASH:h,NO_DOT:_,NO_DOT_SLASH:w,NO_DOTS_SLASH:E,QMARK:L,QMARK_NO_DOT:N,STAR:O,START_ANCHOR:X}=c,U=A=>`(${a}(?:(?!${X}${A.dot?h:d}).)*?)`,x=n.dot?"":_,D=n.dot?L:N,re=n.bash===!0?U(n):O;n.capture&&(re=`(${re})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let S={input:t,index:-1,start:0,dot:n.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};t=Ae.removePrefix(t,S),s=t.length;let j=[],W=[],rt=[],m=i,y,pe=()=>S.index===s-1,H=S.peek=(A=1)=>t[S.index+A],Ue=S.advance=()=>t[++S.index]||"",qe=()=>t.slice(S.index+1),we=(A="",G=0)=>{S.consumed+=A,S.index+=G},Ar=A=>{S.output+=A.output!=null?A.output:A.value,we(A.value)},Tg=()=>{let A=1;for(;H()==="!"&&(H(2)!=="("||H(3)==="?");)Ue(),S.start++,A++;return A%2===0?!1:(S.negated=!0,S.start++,!0)},Er=A=>{S[A]++,rt.push(A)},_t=A=>{S[A]--,rt.pop()},M=A=>{if(m.type==="globstar"){let G=S.braces>0&&(A.type==="comma"||A.type==="brace"),b=A.extglob===!0||j.length&&(A.type==="pipe"||A.type==="paren");A.type!=="slash"&&A.type!=="paren"&&!G&&!b&&(S.output=S.output.slice(0,-m.output.length),m.type="star",m.value="*",m.output=re,S.output+=m.output)}if(j.length&&A.type!=="paren"&&(j[j.length-1].inner+=A.value),(A.value||A.output)&&Ar(A),m&&m.type==="text"&&A.type==="text"){m.value+=A.value,m.output=(m.output||"")+A.value;return}A.prev=m,o.push(A),m=A},Ir=(A,G)=>{let b={...u[G],conditions:1,inner:""};b.prev=m,b.parens=S.parens,b.output=S.output;let P=(n.capture?"(":"")+b.open;Er("parens"),M({type:A,value:G,output:S.output?"":g}),M({type:"paren",extglob:!0,value:Ue(),output:P}),j.push(b)},Rg=A=>{let G=A.close+(n.capture?")":""),b;if(A.type==="negate"){let P=re;if(A.inner&&A.inner.length>1&&A.inner.includes("/")&&(P=U(n)),(P!==re||pe()||/^\)+$/.test(qe()))&&(G=A.close=`)$))${P}`),A.inner.includes("*")&&(b=qe())&&/^\.[^\\/.]+$/.test(b)){let Y=qo(b,{...e,fastpaths:!1}).output;G=A.close=`)${Y})${P})`}A.prev.type==="bos"&&(S.negatedExtglob=!0)}M({type:"paren",extglob:!0,value:y,output:G}),_t("parens")};if(n.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let A=!1,G=t.replace(tw,(b,P,Y,ge,se,ri)=>ge==="\\"?(A=!0,b):ge==="?"?P?P+ge+(se?L.repeat(se.length):""):ri===0?D+(se?L.repeat(se.length):""):L.repeat(Y.length):ge==="."?d.repeat(Y.length):ge==="*"?P?P+ge+(se?re:""):re:P?b:`\\${b}`);return A===!0&&(n.unescape===!0?G=G.replace(/\\/g,""):G=G.replace(/\\+/g,b=>b.length%2===0?"\\\\":b?"\\":"")),G===t&&n.contains===!0?(S.output=t,S):(S.output=Ae.wrapOutput(G,S,e),S)}for(;!pe();){if(y=Ue(),y==="\0")continue;if(y==="\\"){let b=H();if(b==="/"&&n.bash!==!0||b==="."||b===";")continue;if(!b){y+="\\",M({type:"text",value:y});continue}let P=/^\\+/.exec(qe()),Y=0;if(P&&P[0].length>2&&(Y=P[0].length,S.index+=Y,Y%2!==0&&(y+="\\")),n.unescape===!0?y=Ue():y+=Ue(),S.brackets===0){M({type:"text",value:y});continue}}if(S.brackets>0&&(y!=="]"||m.value==="["||m.value==="[^")){if(n.posix!==!1&&y===":"){let b=m.value.slice(1);if(b.includes("[")&&(m.posix=!0,b.includes(":"))){let P=m.value.lastIndexOf("["),Y=m.value.slice(0,P),ge=m.value.slice(P+2),se=Zv[ge];if(se){m.value=Y+se,S.backtrack=!0,Ue(),!i.output&&o.indexOf(m)===1&&(i.output=g);continue}}}(y==="["&&H()!==":"||y==="-"&&H()==="]")&&(y=`\\${y}`),y==="]"&&(m.value==="["||m.value==="[^")&&(y=`\\${y}`),n.posix===!0&&y==="!"&&m.value==="["&&(y="^"),m.value+=y,Ar({value:y});continue}if(S.quotes===1&&y!=='"'){y=Ae.escapeRegex(y),m.value+=y,Ar({value:y});continue}if(y==='"'){S.quotes=S.quotes===1?0:1,n.keepQuotes===!0&&M({type:"text",value:y});continue}if(y==="("){Er("parens"),M({type:"paren",value:y});continue}if(y===")"){if(S.parens===0&&n.strictBrackets===!0)throw new SyntaxError(cn("opening","("));let b=j[j.length-1];if(b&&S.parens===b.parens+1){Rg(j.pop());continue}M({type:"paren",value:y,output:S.parens?")":"\\)"}),_t("parens");continue}if(y==="["){if(n.nobracket===!0||!qe().includes("]")){if(n.nobracket!==!0&&n.strictBrackets===!0)throw new SyntaxError(cn("closing","]"));y=`\\${y}`}else Er("brackets");M({type:"bracket",value:y});continue}if(y==="]"){if(n.nobracket===!0||m&&m.type==="bracket"&&m.value.length===1){M({type:"text",value:y,output:`\\${y}`});continue}if(S.brackets===0){if(n.strictBrackets===!0)throw new SyntaxError(cn("opening","["));M({type:"text",value:y,output:`\\${y}`});continue}_t("brackets");let b=m.value.slice(1);if(m.posix!==!0&&b[0]==="^"&&!b.includes("/")&&(y=`/${y}`),m.value+=y,Ar({value:y}),n.literalBrackets===!1||Ae.hasRegexChars(b))continue;let P=Ae.escapeRegex(m.value);if(S.output=S.output.slice(0,-m.value.length),n.literalBrackets===!0){S.output+=P,m.value=P;continue}m.value=`(${a}${P}|${m.value})`,S.output+=m.value;continue}if(y==="{"&&n.nobrace!==!0){Er("braces");let b={type:"brace",value:y,output:"(",outputIndex:S.output.length,tokensIndex:S.tokens.length};W.push(b),M(b);continue}if(y==="}"){let b=W[W.length-1];if(n.nobrace===!0||!b){M({type:"text",value:y,output:y});continue}let P=")";if(b.dots===!0){let Y=o.slice(),ge=[];for(let se=Y.length-1;se>=0&&(o.pop(),Y[se].type!=="brace");se--)Y[se].type!=="dots"&&ge.unshift(Y[se].value);P=nw(ge,n),S.backtrack=!0}if(b.comma!==!0&&b.dots!==!0){let Y=S.output.slice(0,b.outputIndex),ge=S.tokens.slice(b.tokensIndex);b.value=b.output="\\{",y=P="\\}",S.output=Y;for(let se of ge)S.output+=se.output||se.value}M({type:"brace",value:y,output:P}),_t("braces"),W.pop();continue}if(y==="|"){j.length>0&&j[j.length-1].conditions++,M({type:"text",value:y});continue}if(y===","){let b=y,P=W[W.length-1];P&&rt[rt.length-1]==="braces"&&(P.comma=!0,b="|"),M({type:"comma",value:y,output:b});continue}if(y==="/"){if(m.type==="dot"&&S.index===S.start+1){S.start=S.index+1,S.consumed="",S.output="",o.pop(),m=i;continue}M({type:"slash",value:y,output:p});continue}if(y==="."){if(S.braces>0&&m.type==="dot"){m.value==="."&&(m.output=d);let b=W[W.length-1];m.type="dots",m.output+=y,m.value+=y,b.dots=!0;continue}if(S.braces+S.parens===0&&m.type!=="bos"&&m.type!=="slash"){M({type:"text",value:y,output:d});continue}M({type:"dot",value:y,output:d});continue}if(y==="?"){if(!(m&&m.value==="(")&&n.noextglob!==!0&&H()==="("&&H(2)!=="?"){Ir("qmark",y);continue}if(m&&m.type==="paren"){let P=H(),Y=y;if(P==="<"&&!Ae.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(m.value==="("&&!/[!=<:]/.test(P)||P==="<"&&!/<([!=]|\w+>)/.test(qe()))&&(Y=`\\${y}`),M({type:"text",value:y,output:Y});continue}if(n.dot!==!0&&(m.type==="slash"||m.type==="bos")){M({type:"qmark",value:y,output:N});continue}M({type:"qmark",value:y,output:L});continue}if(y==="!"){if(n.noextglob!==!0&&H()==="("&&(H(2)!=="?"||!/[!=<:]/.test(H(3)))){Ir("negate",y);continue}if(n.nonegate!==!0&&S.index===0){Tg();continue}}if(y==="+"){if(n.noextglob!==!0&&H()==="("&&H(2)!=="?"){Ir("plus",y);continue}if(m&&m.value==="("||n.regex===!1){M({type:"plus",value:y,output:f});continue}if(m&&(m.type==="bracket"||m.type==="paren"||m.type==="brace")||S.parens>0){M({type:"plus",value:y});continue}M({type:"plus",value:f});continue}if(y==="@"){if(n.noextglob!==!0&&H()==="("&&H(2)!=="?"){M({type:"at",extglob:!0,value:y,output:""});continue}M({type:"text",value:y});continue}if(y!=="*"){(y==="$"||y==="^")&&(y=`\\${y}`);let b=ew.exec(qe());b&&(y+=b[0],S.index+=b[0].length),M({type:"text",value:y});continue}if(m&&(m.type==="globstar"||m.star===!0)){m.type="star",m.star=!0,m.value+=y,m.output=re,S.backtrack=!0,S.globstar=!0,we(y);continue}let A=qe();if(n.noextglob!==!0&&/^\([^?]/.test(A)){Ir("star",y);continue}if(m.type==="star"){if(n.noglobstar===!0){we(y);continue}let b=m.prev,P=b.prev,Y=b.type==="slash"||b.type==="bos",ge=P&&(P.type==="star"||P.type==="globstar");if(n.bash===!0&&(!Y||A[0]&&A[0]!=="/")){M({type:"star",value:y,output:""});continue}let se=S.braces>0&&(b.type==="comma"||b.type==="brace"),ri=j.length&&(b.type==="pipe"||b.type==="paren");if(!Y&&b.type!=="paren"&&!se&&!ri){M({type:"star",value:y,output:""});continue}for(;A.slice(0,3)==="/**";){let xr=t[S.index+4];if(xr&&xr!=="/")break;A=A.slice(3),we("/**",3)}if(b.type==="bos"&&pe()){m.type="globstar",m.value+=y,m.output=U(n),S.output=m.output,S.globstar=!0,we(y);continue}if(b.type==="slash"&&b.prev.type!=="bos"&&!ge&&pe()){S.output=S.output.slice(0,-(b.output+m.output).length),b.output=`(?:${b.output}`,m.type="globstar",m.output=U(n)+(n.strictSlashes?")":"|$)"),m.value+=y,S.globstar=!0,S.output+=b.output+m.output,we(y);continue}if(b.type==="slash"&&b.prev.type!=="bos"&&A[0]==="/"){let xr=A[1]!==void 0?"|$":"";S.output=S.output.slice(0,-(b.output+m.output).length),b.output=`(?:${b.output}`,m.type="globstar",m.output=`${U(n)}${p}|${p}${xr})`,m.value+=y,S.output+=b.output+m.output,S.globstar=!0,we(y+Ue()),M({type:"slash",value:"/",output:""});continue}if(b.type==="bos"&&A[0]==="/"){m.type="globstar",m.value+=y,m.output=`(?:^|${p}|${U(n)}${p})`,S.output=m.output,S.globstar=!0,we(y+Ue()),M({type:"slash",value:"/",output:""});continue}S.output=S.output.slice(0,-m.output.length),m.type="globstar",m.output=U(n),m.value+=y,S.output+=m.output,S.globstar=!0,we(y);continue}let G={type:"star",value:y,output:re};if(n.bash===!0){G.output=".*?",(m.type==="bos"||m.type==="slash")&&(G.output=x+G.output),M(G);continue}if(m&&(m.type==="bracket"||m.type==="paren")&&n.regex===!0){G.output=y,M(G);continue}(S.index===S.start||m.type==="slash"||m.type==="dot")&&(m.type==="dot"?(S.output+=w,m.output+=w):n.dot===!0?(S.output+=E,m.output+=E):(S.output+=x,m.output+=x),H()!=="*"&&(S.output+=g,m.output+=g)),M(G)}for(;S.brackets>0;){if(n.strictBrackets===!0)throw new SyntaxError(cn("closing","]"));S.output=Ae.escapeLast(S.output,"["),_t("brackets")}for(;S.parens>0;){if(n.strictBrackets===!0)throw new SyntaxError(cn("closing",")"));S.output=Ae.escapeLast(S.output,"("),_t("parens")}for(;S.braces>0;){if(n.strictBrackets===!0)throw new SyntaxError(cn("closing","}"));S.output=Ae.escapeLast(S.output,"{"),_t("braces")}if(n.strictSlashes!==!0&&(m.type==="star"||m.type==="bracket")&&M({type:"maybe_slash",value:"",output:`${p}?`}),S.backtrack===!0){S.output="";for(let A of S.tokens)S.output+=A.output!=null?A.output:A.value,A.suffix&&(S.output+=A.suffix)}return S};qo.fastpaths=(t,e)=>{let n={...e},r=typeof n.maxLength=="number"?Math.min(ms,n.maxLength):ms,s=t.length;if(s>r)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${r}`);t=If[t]||t;let i=Ae.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:l,DOTS_SLASH:c,NO_DOT:u,NO_DOTS:d,NO_DOTS_SLASH:f,STAR:p,START_ANCHOR:g}=gs.globChars(i),h=n.dot?d:u,_=n.dot?f:u,w=n.capture?"":"?:",E={negated:!1,prefix:""},L=n.bash===!0?".*?":p;n.capture&&(L=`(${L})`);let N=x=>x.noglobstar===!0?L:`(${w}(?:(?!${g}${x.dot?c:o}).)*?)`,O=x=>{switch(x){case"*":return`${h}${l}${L}`;case".*":return`${o}${l}${L}`;case"*.*":return`${h}${L}${o}${l}${L}`;case"*/*":return`${h}${L}${a}${l}${_}${L}`;case"**":return h+N(n);case"**/*":return`(?:${h}${N(n)}${a})?${_}${l}${L}`;case"**/*.*":return`(?:${h}${N(n)}${a})?${_}${L}${o}${l}${L}`;case"**/.*":return`(?:${h}${N(n)}${a})?${o}${l}${L}`;default:{let D=/^(.*?)\.(\w+)$/.exec(x);if(!D)return;let re=O(D[1]);return re?re+o+D[2]:void 0}}},X=Ae.removePrefix(t,E),U=O(X);return U&&n.strictSlashes!==!0&&(U+=`${a}?`),U};xf.exports=qo});var Rf=v((Cx,Tf)=>{"use strict";var rw=require("path"),sw=Ef(),$o=Cf(),Wo=ps(),iw=Zn(),ow=t=>t&&typeof t=="object"&&!Array.isArray(t),ee=(t,e,n=!1)=>{if(Array.isArray(t)){let u=t.map(f=>ee(f,e,n));return f=>{for(let p of u){let g=p(f);if(g)return g}return!1}}let r=ow(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let s=e||{},i=Wo.isWindows(e),o=r?ee.compileRe(t,e):ee.makeRe(t,e,!1,!0),a=o.state;delete o.state;let l=()=>!1;if(s.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};l=ee(s.ignore,u,n)}let c=(u,d=!1)=>{let{isMatch:f,match:p,output:g}=ee.test(u,o,e,{glob:t,posix:i}),h={glob:t,state:a,regex:o,posix:i,input:u,output:g,match:p,isMatch:f};return typeof s.onResult=="function"&&s.onResult(h),f===!1?(h.isMatch=!1,d?h:!1):l(u)?(typeof s.onIgnore=="function"&&s.onIgnore(h),h.isMatch=!1,d?h:!1):(typeof s.onMatch=="function"&&s.onMatch(h),d?h:!0)};return n&&(c.state=a),c};ee.test=(t,e,n,{glob:r,posix:s}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return{isMatch:!1,output:""};let i=n||{},o=i.format||(s?Wo.toPosixSlashes:null),a=t===r,l=a&&o?o(t):t;return a===!1&&(l=o?o(t):t,a=l===r),(a===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?a=ee.matchBase(t,e,n,s):a=e.exec(l)),{isMatch:!!a,match:a,output:l}};ee.matchBase=(t,e,n,r=Wo.isWindows(n))=>(e instanceof RegExp?e:ee.makeRe(e,n)).test(rw.basename(t));ee.isMatch=(t,e,n)=>ee(e,n)(t);ee.parse=(t,e)=>Array.isArray(t)?t.map(n=>ee.parse(n,e)):$o(t,{...e,fastpaths:!1});ee.scan=(t,e)=>sw(t,e);ee.compileRe=(t,e,n=!1,r=!1)=>{if(n===!0)return t.output;let s=e||{},i=s.contains?"":"^",o=s.contains?"":"$",a=`${i}(?:${t.output})${o}`;t&&t.negated===!0&&(a=`^(?!${a}).*$`);let l=ee.toRegex(a,e);return r===!0&&(l.state=t),l};ee.makeRe=(t,e={},n=!1,r=!1)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let s={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]==="."||t[0]==="*")&&(s.output=$o.fastpaths(t,e)),s.output||(s=$o(t,e)),ee.compileRe(s,e,n,r)};ee.toRegex=(t,e)=>{try{let n=e||{};return new RegExp(t,n.flags||(n.nocase?"i":""))}catch(n){if(e&&e.debug===!0)throw n;return/$^/}};ee.constants=iw;Tf.exports=ee});var Go=v((Tx,kf)=>{"use strict";kf.exports=Rf()});var Bf=v((Rx,Hf)=>{"use strict";var nr=require("fs"),{Readable:aw}=require("stream"),tr=require("path"),{promisify:vs}=require("util"),jo=Go(),lw=vs(nr.readdir),cw=vs(nr.stat),Pf=vs(nr.lstat),uw=vs(nr.realpath),dw="!",Of="READDIRP_RECURSIVE_ERROR",fw=new Set(["ENOENT","EPERM","EACCES","ELOOP",Of]),Vo="files",Df="directories",_s="files_directories",ys="all",Mf=[Vo,Df,_s,ys],hw=t=>fw.has(t.code),[Lf,pw]=process.versions.node.split(".").slice(0,2).map(t=>Number.parseInt(t,10)),gw=process.platform==="win32"&&(Lf>10||Lf===10&&pw>=5),Nf=t=>{if(t!==void 0){if(typeof t=="function")return t;if(typeof t=="string"){let e=jo(t.trim());return n=>e(n.basename)}if(Array.isArray(t)){let e=[],n=[];for(let r of t){let s=r.trim();s.charAt(0)===dw?n.push(jo(s.slice(1))):e.push(jo(s))}return n.length>0?e.length>0?r=>e.some(s=>s(r.basename))&&!n.some(s=>s(r.basename)):r=>!n.some(s=>s(r.basename)):r=>e.some(s=>s(r.basename))}}},Ss=class t extends aw{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:Vo,lstat:!1,depth:2147483648,alwaysStat:!1}}constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark||4096});let n={...t.defaultOptions,...e},{root:r,type:s}=n;this._fileFilter=Nf(n.fileFilter),this._directoryFilter=Nf(n.directoryFilter);let i=n.lstat?Pf:cw;gw?this._stat=o=>i(o,{bigint:!0}):this._stat=i,this._maxDepth=n.depth,this._wantsDir=[Df,_s,ys].includes(s),this._wantsFile=[Vo,_s,ys].includes(s),this._wantsEverything=s===ys,this._root=tr.resolve(r),this._isDirent="Dirent"in nr&&!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(r,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let{path:n,depth:r,files:s=[]}=this.parent||{};if(s.length>0){let i=s.splice(0,e).map(o=>this._formatEntry(o,n));for(let o of await Promise.all(i)){if(this.destroyed)return;let a=await this._getEntryType(o);a==="directory"&&this._directoryFilter(o)?(r<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,r+1)),this._wantsDir&&(this.push(o),e--)):(a==="file"||this._includeAsFile(o))&&this._fileFilter(o)&&this._wantsFile&&(this.push(o),e--)}}else{let i=this.parents.pop();if(!i){this.push(null);break}if(this.parent=await i,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await lw(e,this._rdOptions)}catch(s){this._onError(s)}return{files:r,depth:n,path:e}}async _formatEntry(e,n){let r;try{let s=this._isDirent?e.name:e,i=tr.resolve(tr.join(n,s));r={path:tr.relative(this._root,i),fullPath:i,basename:s},r[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(s){this._onError(s)}return r}_onError(e){hw(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){let n=e&&e[this._statsProp];if(n){if(n.isFile())return"file";if(n.isDirectory())return"directory";if(n&&n.isSymbolicLink()){let r=e.fullPath;try{let s=await uw(r),i=await Pf(s);if(i.isFile())return"file";if(i.isDirectory()){let o=s.length;if(r.startsWith(s)&&r.substr(o,1)===tr.sep){let a=new Error(`Circular symlink detected: "${r}" points to "${s}"`);return a.code=Of,this._onError(a)}return"directory"}}catch(s){this._onError(s)}}}}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}},un=(t,e={})=>{let n=e.entryType||e.type;if(n==="both"&&(n=_s),n&&(e.type=n),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!Mf.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${Mf.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=t,new Ss(e)},mw=(t,e={})=>new Promise((n,r)=>{let s=[];un(t,e).on("data",i=>s.push(i)).on("end",()=>n(s)).on("error",i=>r(i))});un.promise=mw;un.ReaddirpStream=Ss;un.default=un;Hf.exports=un});var zo=v((kx,Ff)=>{Ff.exports=function(t,e){if(typeof t!="string")throw new TypeError("expected path to be a string");if(t==="\\"||t==="/")return"/";var n=t.length;if(n<=1)return t;var r="";if(n>4&&t[3]==="\\"){var s=t[2];(s==="?"||s===".")&&t.slice(0,2)==="\\\\"&&(t=t.slice(2),r="//")}var i=t.split(/[/\\]+/);return e!==!1&&i[i.length-1]===""&&i.pop(),r+i.join("/")}});var jf=v((Wf,Gf)=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var $f=Go(),yw=zo(),Uf="!",_w={returnIndex:!1},Sw=t=>Array.isArray(t)?t:[t],vw=(t,e)=>{if(typeof t=="function")return t;if(typeof t=="string"){let n=$f(t,e);return r=>t===r||n(r)}return t instanceof RegExp?n=>t.test(n):n=>!1},qf=(t,e,n,r)=>{let s=Array.isArray(n),i=s?n[0]:n;if(!s&&typeof i!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(i));let o=yw(i,!1);for(let l=0;l<e.length;l++){let c=e[l];if(c(o))return r?-1:!1}let a=s&&[o].concat(n.slice(1));for(let l=0;l<t.length;l++){let c=t[l];if(s?c(...a):c(o))return r?l:!0}return r?-1:!1},Yo=(t,e,n=_w)=>{if(t==null)throw new TypeError("anymatch: specify first argument");let r=typeof n=="boolean"?{returnIndex:n}:n,s=r.returnIndex||!1,i=Sw(t),o=i.filter(l=>typeof l=="string"&&l.charAt(0)===Uf).map(l=>l.slice(1)).map(l=>$f(l,r)),a=i.filter(l=>typeof l!="string"||typeof l=="string"&&l.charAt(0)!==Uf).map(l=>vw(l,r));return e==null?(l,c=!1)=>qf(a,o,l,typeof c=="boolean"?c:!1):qf(a,o,e,s)};Yo.default=Yo;Gf.exports=Yo});var zf=v((Px,Vf)=>{Vf.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var n;n=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(n[2])return!0;e=e.slice(n.index+n[0].length)}return!1}});var Ko=v((Mx,Kf)=>{var ww=zf(),Yf={"{":"}","(":")","[":"]"},bw=function(t){if(t[0]==="!")return!0;for(var e=0,n=-2,r=-2,s=-2,i=-2,o=-2;e<t.length;){if(t[e]==="*"||t[e+1]==="?"&&/[\].+)]/.test(t[e])||r!==-1&&t[e]==="["&&t[e+1]!=="]"&&(r<e&&(r=t.indexOf("]",e)),r>e&&(o===-1||o>r||(o=t.indexOf("\\",e),o===-1||o>r)))||s!==-1&&t[e]==="{"&&t[e+1]!=="}"&&(s=t.indexOf("}",e),s>e&&(o=t.indexOf("\\",e),o===-1||o>s))||i!==-1&&t[e]==="("&&t[e+1]==="?"&&/[:!=]/.test(t[e+2])&&t[e+3]!==")"&&(i=t.indexOf(")",e),i>e&&(o=t.indexOf("\\",e),o===-1||o>i))||n!==-1&&t[e]==="("&&t[e+1]!=="|"&&(n<e&&(n=t.indexOf("|",e)),n!==-1&&t[n+1]!==")"&&(i=t.indexOf(")",n),i>n&&(o=t.indexOf("\\",n),o===-1||o>i))))return!0;if(t[e]==="\\"){var a=t[e+1];e+=2;var l=Yf[a];if(l){var c=t.indexOf(l,e);c!==-1&&(e=c+1)}if(t[e]==="!")return!0}else e++}return!1},Aw=function(t){if(t[0]==="!")return!0;for(var e=0;e<t.length;){if(/[*?{}()[\]]/.test(t[e]))return!0;if(t[e]==="\\"){var n=t[e+1];e+=2;var r=Yf[n];if(r){var s=t.indexOf(r,e);s!==-1&&(e=s+1)}if(t[e]==="!")return!0}else e++}return!1};Kf.exports=function(e,n){if(typeof e!="string"||e==="")return!1;if(ww(e))return!0;var r=bw;return n&&n.strict===!1&&(r=Aw),r(e)}});var Qf=v((Lx,Jf)=>{"use strict";var Ew=Ko(),Iw=require("path").posix.dirname,xw=require("os").platform()==="win32",Jo="/",Cw=/\\/g,Tw=/[\{\[].*[\}\]]$/,Rw=/(^|[^\\])([\{\[]|\([^\)]+$)/,kw=/\\([\!\*\?\|\[\]\(\)\{\}])/g;Jf.exports=function(e,n){var r=Object.assign({flipBackslashes:!0},n);r.flipBackslashes&&xw&&e.indexOf(Jo)<0&&(e=e.replace(Cw,Jo)),Tw.test(e)&&(e+=Jo),e+="a";do e=Iw(e);while(Ew(e)||Rw.test(e));return e.replace(kw,"$1")}});var ws=v(Pe=>{"use strict";Pe.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;Pe.find=(t,e)=>t.nodes.find(n=>n.type===e);Pe.exceedsLimit=(t,e,n=1,r)=>r===!1||!Pe.isInteger(t)||!Pe.isInteger(e)?!1:(Number(e)-Number(t))/Number(n)>=r;Pe.escapeNode=(t,e=0,n)=>{let r=t.nodes[e];r&&(n&&r.type===n||r.type==="open"||r.type==="close")&&r.escaped!==!0&&(r.value="\\"+r.value,r.escaped=!0)};Pe.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;Pe.isInvalidBrace=t=>t.type!=="brace"?!1:t.invalid===!0||t.dollar?!0:t.commas>>0+t.ranges>>0===0||t.open!==!0||t.close!==!0?(t.invalid=!0,!0):!1;Pe.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;Pe.reduce=t=>t.reduce((e,n)=>(n.type==="text"&&e.push(n.value),n.type==="range"&&(n.type="text"),e),[]);Pe.flatten=(...t)=>{let e=[],n=r=>{for(let s=0;s<r.length;s++){let i=r[s];if(Array.isArray(i)){n(i);continue}i!==void 0&&e.push(i)}return e};return n(t),e}});var bs=v((Ox,Zf)=>{"use strict";var Xf=ws();Zf.exports=(t,e={})=>{let n=(r,s={})=>{let i=e.escapeInvalid&&Xf.isInvalidBrace(s),o=r.invalid===!0&&e.escapeInvalid===!0,a="";if(r.value)return(i||o)&&Xf.isOpenOrClose(r)?"\\"+r.value:r.value;if(r.value)return r.value;if(r.nodes)for(let l of r.nodes)a+=n(l);return a};return n(t)}});var th=v((Dx,eh)=>{"use strict";eh.exports=function(t){return typeof t=="number"?t-t===0:typeof t=="string"&&t.trim()!==""?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var uh=v((Hx,ch)=>{"use strict";var nh=th(),Ot=(t,e,n)=>{if(nh(t)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||t===e)return String(t);if(nh(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let r={relaxZeros:!0,...n};typeof r.strictZeros=="boolean"&&(r.relaxZeros=r.strictZeros===!1);let s=String(r.relaxZeros),i=String(r.shorthand),o=String(r.capture),a=String(r.wrap),l=t+":"+e+"="+s+i+o+a;if(Ot.cache.hasOwnProperty(l))return Ot.cache[l].result;let c=Math.min(t,e),u=Math.max(t,e);if(Math.abs(c-u)===1){let h=t+"|"+e;return r.capture?`(${h})`:r.wrap===!1?h:`(?:${h})`}let d=lh(t)||lh(e),f={min:t,max:e,a:c,b:u},p=[],g=[];if(d&&(f.isPadded=d,f.maxLen=String(f.max).length),c<0){let h=u<0?Math.abs(u):1;g=rh(h,Math.abs(c),f,r),c=f.a=0}return u>=0&&(p=rh(c,u,f,r)),f.negatives=g,f.positives=p,f.result=Pw(g,p,r),r.capture===!0?f.result=`(${f.result})`:r.wrap!==!1&&p.length+g.length>1&&(f.result=`(?:${f.result})`),Ot.cache[l]=f,f.result};function Pw(t,e,n){let r=Qo(t,e,"-",!1,n)||[],s=Qo(e,t,"",!1,n)||[],i=Qo(t,e,"-?",!0,n)||[];return r.concat(i).concat(s).join("|")}function Mw(t,e){let n=1,r=1,s=ih(t,n),i=new Set([e]);for(;t<=s&&s<=e;)i.add(s),n+=1,s=ih(t,n);for(s=oh(e+1,r)-1;t<s&&s<=e;)i.add(s),r+=1,s=oh(e+1,r)-1;return i=[...i],i.sort(Ow),i}function Lw(t,e,n){if(t===e)return{pattern:t,count:[],digits:0};let r=Nw(t,e),s=r.length,i="",o=0;for(let a=0;a<s;a++){let[l,c]=r[a];l===c?i+=l:l!=="0"||c!=="9"?i+=Dw(l,c,n):o++}return o&&(i+=n.shorthand===!0?"\\d":"[0-9]"),{pattern:i,count:[o],digits:s}}function rh(t,e,n,r){let s=Mw(t,e),i=[],o=t,a;for(let l=0;l<s.length;l++){let c=s[l],u=Lw(String(o),String(c),r),d="";if(!n.isPadded&&a&&a.pattern===u.pattern){a.count.length>1&&a.count.pop(),a.count.push(u.count[0]),a.string=a.pattern+ah(a.count),o=c+1;continue}n.isPadded&&(d=Hw(c,n,r)),u.string=d+u.pattern+ah(u.count),i.push(u),o=c+1,a=u}return i}function Qo(t,e,n,r,s){let i=[];for(let o of t){let{string:a}=o;!r&&!sh(e,"string",a)&&i.push(n+a),r&&sh(e,"string",a)&&i.push(n+a)}return i}function Nw(t,e){let n=[];for(let r=0;r<t.length;r++)n.push([t[r],e[r]]);return n}function Ow(t,e){return t>e?1:e>t?-1:0}function sh(t,e,n){return t.some(r=>r[e]===n)}function ih(t,e){return Number(String(t).slice(0,-e)+"9".repeat(e))}function oh(t,e){return t-t%Math.pow(10,e)}function ah(t){let[e=0,n=""]=t;return n||e>1?`{${e+(n?","+n:"")}}`:""}function Dw(t,e,n){return`[${t}${e-t===1?"":"-"}${e}]`}function lh(t){return/^-?(0+)\d/.test(t)}function Hw(t,e,n){if(!e.isPadded)return t;let r=Math.abs(e.maxLen-String(t).length),s=n.relaxZeros!==!1;switch(r){case 0:return"";case 1:return s?"0?":"0";case 2:return s?"0{0,2}":"00";default:return s?`0{0,${r}}`:`0{${r}}`}}Ot.cache={};Ot.clearCache=()=>Ot.cache={};ch.exports=Ot});var ea=v((Bx,yh)=>{"use strict";var Bw=require("util"),fh=uh(),dh=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),Fw=t=>e=>t===!0?Number(e):String(e),Xo=t=>typeof t=="number"||typeof t=="string"&&t!=="",rr=t=>Number.isInteger(+t),Zo=t=>{let e=`${t}`,n=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++n]==="0";);return n>0},Uw=(t,e,n)=>typeof t=="string"||typeof e=="string"?!0:n.stringify===!0,qw=(t,e,n)=>{if(e>0){let r=t[0]==="-"?"-":"";r&&(t=t.slice(1)),t=r+t.padStart(r?e-1:e,"0")}return n===!1?String(t):t},Es=(t,e)=>{let n=t[0]==="-"?"-":"";for(n&&(t=t.slice(1),e--);t.length<e;)t="0"+t;return n?"-"+t:t},$w=(t,e,n)=>{t.negatives.sort((a,l)=>a<l?-1:a>l?1:0),t.positives.sort((a,l)=>a<l?-1:a>l?1:0);let r=e.capture?"":"?:",s="",i="",o;return t.positives.length&&(s=t.positives.map(a=>Es(String(a),n)).join("|")),t.negatives.length&&(i=`-(${r}${t.negatives.map(a=>Es(String(a),n)).join("|")})`),s&&i?o=`${s}|${i}`:o=s||i,e.wrap?`(${r}${o})`:o},hh=(t,e,n,r)=>{if(n)return fh(t,e,{wrap:!1,...r});let s=String.fromCharCode(t);if(t===e)return s;let i=String.fromCharCode(e);return`[${s}-${i}]`},ph=(t,e,n)=>{if(Array.isArray(t)){let r=n.wrap===!0,s=n.capture?"":"?:";return r?`(${s}${t.join("|")})`:t.join("|")}return fh(t,e,n)},gh=(...t)=>new RangeError("Invalid range arguments: "+Bw.inspect(...t)),mh=(t,e,n)=>{if(n.strictRanges===!0)throw gh([t,e]);return[]},Ww=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},Gw=(t,e,n=1,r={})=>{let s=Number(t),i=Number(e);if(!Number.isInteger(s)||!Number.isInteger(i)){if(r.strictRanges===!0)throw gh([t,e]);return[]}s===0&&(s=0),i===0&&(i=0);let o=s>i,a=String(t),l=String(e),c=String(n);n=Math.max(Math.abs(n),1);let u=Zo(a)||Zo(l)||Zo(c),d=u?Math.max(a.length,l.length,c.length):0,f=u===!1&&Uw(t,e,r)===!1,p=r.transform||Fw(f);if(r.toRegex&&n===1)return hh(Es(t,d),Es(e,d),!0,r);let g={negatives:[],positives:[]},h=E=>g[E<0?"negatives":"positives"].push(Math.abs(E)),_=[],w=0;for(;o?s>=i:s<=i;)r.toRegex===!0&&n>1?h(s):_.push(qw(p(s,w),d,f)),s=o?s-n:s+n,w++;return r.toRegex===!0?n>1?$w(g,r,d):ph(_,null,{wrap:!1,...r}):_},jw=(t,e,n=1,r={})=>{if(!rr(t)&&t.length>1||!rr(e)&&e.length>1)return mh(t,e,r);let s=r.transform||(f=>String.fromCharCode(f)),i=`${t}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=i>o,l=Math.min(i,o),c=Math.max(i,o);if(r.toRegex&&n===1)return hh(l,c,!1,r);let u=[],d=0;for(;a?i>=o:i<=o;)u.push(s(i,d)),i=a?i-n:i+n,d++;return r.toRegex===!0?ph(u,null,{wrap:!1,options:r}):u},As=(t,e,n,r={})=>{if(e==null&&Xo(t))return[t];if(!Xo(t)||!Xo(e))return mh(t,e,r);if(typeof n=="function")return As(t,e,1,{transform:n});if(dh(n))return As(t,e,0,n);let s={...r};return s.capture===!0&&(s.wrap=!0),n=n||s.step||1,rr(n)?rr(t)&&rr(e)?Gw(t,e,n,s):jw(t,e,Math.max(Math.abs(n),1),s):n!=null&&!dh(n)?Ww(n,s):As(t,e,1,n)};yh.exports=As});var vh=v((Fx,Sh)=>{"use strict";var Vw=ea(),_h=ws(),zw=(t,e={})=>{let n=(r,s={})=>{let i=_h.isInvalidBrace(s),o=r.invalid===!0&&e.escapeInvalid===!0,a=i===!0||o===!0,l=e.escapeInvalid===!0?"\\":"",c="";if(r.isOpen===!0)return l+r.value;if(r.isClose===!0)return console.log("node.isClose",l,r.value),l+r.value;if(r.type==="open")return a?l+r.value:"(";if(r.type==="close")return a?l+r.value:")";if(r.type==="comma")return r.prev.type==="comma"?"":a?r.value:"|";if(r.value)return r.value;if(r.nodes&&r.ranges>0){let u=_h.reduce(r.nodes),d=Vw(...u,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(d.length!==0)return u.length>1&&d.length>1?`(${d})`:d}if(r.nodes)for(let u of r.nodes)c+=n(u,r);return c};return n(t)};Sh.exports=zw});var Ah=v((Ux,bh)=>{"use strict";var Yw=ea(),wh=bs(),dn=ws(),Dt=(t="",e="",n=!1)=>{let r=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return n?dn.flatten(e).map(s=>`{${s}}`):e;for(let s of t)if(Array.isArray(s))for(let i of s)r.push(Dt(i,e,n));else for(let i of e)n===!0&&typeof i=="string"&&(i=`{${i}}`),r.push(Array.isArray(i)?Dt(s,i,n):s+i);return dn.flatten(r)},Kw=(t,e={})=>{let n=e.rangeLimit===void 0?1e3:e.rangeLimit,r=(s,i={})=>{s.queue=[];let o=i,a=i.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(s.invalid||s.dollar){a.push(Dt(a.pop(),wh(s,e)));return}if(s.type==="brace"&&s.invalid!==!0&&s.nodes.length===2){a.push(Dt(a.pop(),["{}"]));return}if(s.nodes&&s.ranges>0){let d=dn.reduce(s.nodes);if(dn.exceedsLimit(...d,e.step,n))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let f=Yw(...d,e);f.length===0&&(f=wh(s,e)),a.push(Dt(a.pop(),f)),s.nodes=[];return}let l=dn.encloseBrace(s),c=s.queue,u=s;for(;u.type!=="brace"&&u.type!=="root"&&u.parent;)u=u.parent,c=u.queue;for(let d=0;d<s.nodes.length;d++){let f=s.nodes[d];if(f.type==="comma"&&s.type==="brace"){d===1&&c.push(""),c.push("");continue}if(f.type==="close"){a.push(Dt(a.pop(),c,l));continue}if(f.value&&f.type!=="open"){c.push(Dt(c.pop(),f.value));continue}f.nodes&&r(f,s)}return c};return dn.flatten(r(t))};bh.exports=Kw});var Ih=v((qx,Eh)=>{"use strict";Eh.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
21
- `,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var kh=v(($x,Rh)=>{"use strict";var Jw=bs(),{MAX_LENGTH:xh,CHAR_BACKSLASH:ta,CHAR_BACKTICK:Qw,CHAR_COMMA:Xw,CHAR_DOT:Zw,CHAR_LEFT_PARENTHESES:e0,CHAR_RIGHT_PARENTHESES:t0,CHAR_LEFT_CURLY_BRACE:n0,CHAR_RIGHT_CURLY_BRACE:r0,CHAR_LEFT_SQUARE_BRACKET:Ch,CHAR_RIGHT_SQUARE_BRACKET:Th,CHAR_DOUBLE_QUOTE:s0,CHAR_SINGLE_QUOTE:i0,CHAR_NO_BREAK_SPACE:o0,CHAR_ZERO_WIDTH_NOBREAK_SPACE:a0}=Ih(),l0=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let n=e||{},r=typeof n.maxLength=="number"?Math.min(xh,n.maxLength):xh;if(t.length>r)throw new SyntaxError(`Input length (${t.length}), exceeds max characters (${r})`);let s={type:"root",input:t,nodes:[]},i=[s],o=s,a=s,l=0,c=t.length,u=0,d=0,f,p=()=>t[u++],g=h=>{if(h.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&h.type==="text"){a.value+=h.value;return}return o.nodes.push(h),h.parent=o,h.prev=a,a=h,h};for(g({type:"bos"});u<c;)if(o=i[i.length-1],f=p(),!(f===a0||f===o0)){if(f===ta){g({type:"text",value:(e.keepEscaping?f:"")+p()});continue}if(f===Th){g({type:"text",value:"\\"+f});continue}if(f===Ch){l++;let h;for(;u<c&&(h=p());){if(f+=h,h===Ch){l++;continue}if(h===ta){f+=p();continue}if(h===Th&&(l--,l===0))break}g({type:"text",value:f});continue}if(f===e0){o=g({type:"paren",nodes:[]}),i.push(o),g({type:"text",value:f});continue}if(f===t0){if(o.type!=="paren"){g({type:"text",value:f});continue}o=i.pop(),g({type:"text",value:f}),o=i[i.length-1];continue}if(f===s0||f===i0||f===Qw){let h=f,_;for(e.keepQuotes!==!0&&(f="");u<c&&(_=p());){if(_===ta){f+=_+p();continue}if(_===h){e.keepQuotes===!0&&(f+=_);break}f+=_}g({type:"text",value:f});continue}if(f===n0){d++;let _={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:d,commas:0,ranges:0,nodes:[]};o=g(_),i.push(o),g({type:"open",value:f});continue}if(f===r0){if(o.type!=="brace"){g({type:"text",value:f});continue}let h="close";o=i.pop(),o.close=!0,g({type:h,value:f}),d--,o=i[i.length-1];continue}if(f===Xw&&d>0){if(o.ranges>0){o.ranges=0;let h=o.nodes.shift();o.nodes=[h,{type:"text",value:Jw(o)}]}g({type:"comma",value:f}),o.commas++;continue}if(f===Zw&&d>0&&o.commas===0){let h=o.nodes;if(d===0||h.length===0){g({type:"text",value:f});continue}if(a.type==="dot"){if(o.range=[],a.value+=f,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){h.pop();let _=h[h.length-1];_.value+=a.value+f,a=_,o.ranges--;continue}g({type:"dot",value:f});continue}g({type:"text",value:f})}do if(o=i.pop(),o.type!=="root"){o.nodes.forEach(w=>{w.nodes||(w.type==="open"&&(w.isOpen=!0),w.type==="close"&&(w.isClose=!0),w.nodes||(w.type="text"),w.invalid=!0)});let h=i[i.length-1],_=h.nodes.indexOf(o);h.nodes.splice(_,1,...o.nodes)}while(i.length>0);return g({type:"eos"}),s};Rh.exports=l0});var Lh=v((Wx,Mh)=>{"use strict";var Ph=bs(),c0=vh(),u0=Ah(),d0=kh(),Ee=(t,e={})=>{let n=[];if(Array.isArray(t))for(let r of t){let s=Ee.create(r,e);Array.isArray(s)?n.push(...s):n.push(s)}else n=[].concat(Ee.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(n=[...new Set(n)]),n};Ee.parse=(t,e={})=>d0(t,e);Ee.stringify=(t,e={})=>Ph(typeof t=="string"?Ee.parse(t,e):t,e);Ee.compile=(t,e={})=>(typeof t=="string"&&(t=Ee.parse(t,e)),c0(t,e));Ee.expand=(t,e={})=>{typeof t=="string"&&(t=Ee.parse(t,e));let n=u0(t,e);return e.noempty===!0&&(n=n.filter(Boolean)),e.nodupes===!0&&(n=[...new Set(n)]),n};Ee.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?Ee.compile(t,e):Ee.expand(t,e);Mh.exports=Ee});var Nh=v((Gx,f0)=>{f0.exports=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]});var Dh=v((jx,Oh)=>{Oh.exports=Nh()});var Bh=v((Vx,Hh)=>{"use strict";var h0=require("path"),p0=Dh(),g0=new Set(p0);Hh.exports=t=>g0.has(h0.extname(t).slice(1).toLowerCase())});var Is=v(I=>{"use strict";var{sep:m0}=require("path"),{platform:na}=process,y0=require("os");I.EV_ALL="all";I.EV_READY="ready";I.EV_ADD="add";I.EV_CHANGE="change";I.EV_ADD_DIR="addDir";I.EV_UNLINK="unlink";I.EV_UNLINK_DIR="unlinkDir";I.EV_RAW="raw";I.EV_ERROR="error";I.STR_DATA="data";I.STR_END="end";I.STR_CLOSE="close";I.FSEVENT_CREATED="created";I.FSEVENT_MODIFIED="modified";I.FSEVENT_DELETED="deleted";I.FSEVENT_MOVED="moved";I.FSEVENT_CLONED="cloned";I.FSEVENT_UNKNOWN="unknown";I.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;I.FSEVENT_TYPE_FILE="file";I.FSEVENT_TYPE_DIRECTORY="directory";I.FSEVENT_TYPE_SYMLINK="symlink";I.KEY_LISTENERS="listeners";I.KEY_ERR="errHandlers";I.KEY_RAW="rawEmitters";I.HANDLER_KEYS=[I.KEY_LISTENERS,I.KEY_ERR,I.KEY_RAW];I.DOT_SLASH=`.${m0}`;I.BACK_SLASH_RE=/\\/g;I.DOUBLE_SLASH_RE=/\/\//;I.SLASH_OR_BACK_SLASH_RE=/[/\\]/;I.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;I.REPLACER_RE=/^\.[/\\]/;I.SLASH="/";I.SLASH_SLASH="//";I.BRACE_START="{";I.BANG="!";I.ONE_DOT=".";I.TWO_DOTS="..";I.STAR="*";I.GLOBSTAR="**";I.ROOT_GLOBSTAR="/**/*";I.SLASH_GLOBSTAR="/**";I.DIR_SUFFIX="Dir";I.ANYMATCH_OPTS={dot:!0};I.STRING_TYPE="string";I.FUNCTION_TYPE="function";I.EMPTY_STR="";I.EMPTY_FN=()=>{};I.IDENTITY_FN=t=>t;I.isWindows=na==="win32";I.isMacos=na==="darwin";I.isLinux=na==="linux";I.isIBMi=y0.type()==="OS400"});var Gh=v((Yx,Wh)=>{"use strict";var et=require("fs"),ce=require("path"),{promisify:ar}=require("util"),_0=Bh(),{isWindows:S0,isLinux:v0,EMPTY_FN:w0,EMPTY_STR:b0,KEY_LISTENERS:fn,KEY_ERR:ra,KEY_RAW:sr,HANDLER_KEYS:A0,EV_CHANGE:Cs,EV_ADD:xs,EV_ADD_DIR:E0,EV_ERROR:Uh,STR_DATA:I0,STR_END:x0,BRACE_START:C0,STAR:T0}=Is(),R0="watch",k0=ar(et.open),qh=ar(et.stat),P0=ar(et.lstat),M0=ar(et.close),sa=ar(et.realpath),L0={lstat:P0,stat:qh},oa=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},ir=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},N0=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},or=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},$h=t=>t instanceof Set?t.size===0:!t,Ts=new Map;function Fh(t,e,n,r,s){let i=(o,a)=>{n(t),s(o,a,{watchedPath:t}),a&&t!==a&&Rs(ce.resolve(t,a),fn,ce.join(t,a))};try{return et.watch(t,e,i)}catch(o){r(o)}}var Rs=(t,e,n,r,s)=>{let i=Ts.get(t);i&&oa(i[e],o=>{o(n,r,s)})},O0=(t,e,n,r)=>{let{listener:s,errHandler:i,rawEmitter:o}=r,a=Ts.get(e),l;if(!n.persistent)return l=Fh(t,n,s,i,o),l.close.bind(l);if(a)ir(a,fn,s),ir(a,ra,i),ir(a,sr,o);else{if(l=Fh(t,n,Rs.bind(null,e,fn),i,Rs.bind(null,e,sr)),!l)return;l.on(Uh,async c=>{let u=Rs.bind(null,e,ra);if(a.watcherUnusable=!0,S0&&c.code==="EPERM")try{let d=await k0(t,"r");await M0(d),u(c)}catch{}else u(c)}),a={listeners:s,errHandlers:i,rawEmitters:o,watcher:l},Ts.set(e,a)}return()=>{or(a,fn,s),or(a,ra,i),or(a,sr,o),$h(a.listeners)&&(a.watcher.close(),Ts.delete(e),A0.forEach(N0(a)),a.watcher=void 0,Object.freeze(a))}},ia=new Map,D0=(t,e,n,r)=>{let{listener:s,rawEmitter:i}=r,o=ia.get(e),a=new Set,l=new Set,c=o&&o.options;return c&&(c.persistent<n.persistent||c.interval>n.interval)&&(a=o.listeners,l=o.rawEmitters,et.unwatchFile(e),o=void 0),o?(ir(o,fn,s),ir(o,sr,i)):(o={listeners:s,rawEmitters:i,options:n,watcher:et.watchFile(e,n,(u,d)=>{oa(o.rawEmitters,p=>{p(Cs,e,{curr:u,prev:d})});let f=u.mtimeMs;(u.size!==d.size||f>d.mtimeMs||f===0)&&oa(o.listeners,p=>p(t,u))})},ia.set(e,o)),()=>{or(o,fn,s),or(o,sr,i),$h(o.listeners)&&(ia.delete(e),et.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},aa=class{constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,s=ce.dirname(e),i=ce.basename(e);this.fsw._getWatchedDir(s).add(i);let a=ce.resolve(e),l={persistent:r.persistent};n||(n=w0);let c;return r.usePolling?(l.interval=r.enableBinaryInterval&&_0(i)?r.binaryInterval:r.interval,c=D0(e,a,l,{listener:n,rawEmitter:this.fsw._emitRaw})):c=O0(e,a,l,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),c}_handleFile(e,n,r){if(this.fsw.closed)return;let s=ce.dirname(e),i=ce.basename(e),o=this.fsw._getWatchedDir(s),a=n;if(o.has(i))return;let l=async(u,d)=>{if(this.fsw._throttle(R0,e,5)){if(!d||d.mtimeMs===0)try{let f=await qh(e);if(this.fsw.closed)return;let p=f.atimeMs,g=f.mtimeMs;(!p||p<=g||g!==a.mtimeMs)&&this.fsw._emit(Cs,e,f),v0&&a.ino!==f.ino?(this.fsw._closeFile(u),a=f,this.fsw._addPathCloser(u,this._watchWithNodeFs(e,l))):a=f}catch{this.fsw._remove(s,i)}else if(o.has(i)){let f=d.atimeMs,p=d.mtimeMs;(!f||f<=p||p!==a.mtimeMs)&&this.fsw._emit(Cs,e,d),a=d}}},c=this._watchWithNodeFs(e,l);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(xs,e,0))return;this.fsw._emit(xs,e,n)}return c}async _handleSymlink(e,n,r,s){if(this.fsw.closed)return;let i=e.fullPath,o=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await sa(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(s)?this.fsw._symlinkPaths.get(i)!==a&&(this.fsw._symlinkPaths.set(i,a),this.fsw._emit(Cs,r,e.stats)):(o.add(s),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(xs,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,n,r,s,i,o,a){if(e=ce.join(e,b0),!r.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let l=this.fsw._getWatchedDir(r.path),c=new Set,u=this.fsw._readdirp(e,{fileFilter:d=>r.filterPath(d),directoryFilter:d=>r.filterDir(d),depth:0}).on(I0,async d=>{if(this.fsw.closed){u=void 0;return}let f=d.path,p=ce.join(e,f);if(c.add(f),!(d.stats.isSymbolicLink()&&await this._handleSymlink(d,e,p,f))){if(this.fsw.closed){u=void 0;return}(f===s||!s&&!l.has(f))&&(this.fsw._incrReadyCount(),p=ce.join(i,ce.relative(i,p)),this._addToNodeFs(p,n,r,o+1))}}).on(Uh,this._boundHandleError);return new Promise(d=>u.once(x0,()=>{if(this.fsw.closed){u=void 0;return}let f=a?a.clear():!1;d(),l.getChildren().filter(p=>p!==e&&!c.has(p)&&(!r.hasGlob||r.filterPath({fullPath:ce.resolve(e,p)}))).forEach(p=>{this.fsw._remove(e,p)}),u=void 0,f&&this._handleRead(e,!1,r,s,i,o,a)}))}async _handleDir(e,n,r,s,i,o,a){let l=this.fsw._getWatchedDir(ce.dirname(e)),c=l.has(ce.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!i&&!c&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(E0,e,n),l.add(ce.basename(e)),this.fsw._getWatchedDir(e);let u,d,f=this.fsw.options.depth;if((f==null||s<=f)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(e,r,o,i,e,s,u),this.fsw.closed))return;d=this._watchWithNodeFs(e,(p,g)=>{g&&g.mtimeMs===0||this._handleRead(p,!1,o,i,e,s,u)})}return d}async _addToNodeFs(e,n,r,s,i){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,s);!a.hasGlob&&r&&(a.hasGlob=r.hasGlob,a.globFilter=r.globFilter,a.filterPath=l=>r.filterPath(l),a.filterDir=l=>r.filterDir(l));try{let l=await L0[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))return o(),!1;let c=this.fsw.options.followSymlinks&&!e.includes(T0)&&!e.includes(C0),u;if(l.isDirectory()){let d=ce.resolve(e),f=c?await sa(e):e;if(this.fsw.closed||(u=await this._handleDir(a.watchPath,l,n,s,i,a,f),this.fsw.closed))return;d!==f&&f!==void 0&&this.fsw._symlinkPaths.set(d,f)}else if(l.isSymbolicLink()){let d=c?await sa(e):e;if(this.fsw.closed)return;let f=ce.dirname(a.watchPath);if(this.fsw._getWatchedDir(f).add(a.watchPath),this.fsw._emit(xs,a.watchPath,l),u=await this._handleDir(f,l,n,s,e,a,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(ce.resolve(e),d)}else u=this._handleFile(a.watchPath,l,n);return o(),this.fsw._addPathCloser(e,u),!1}catch(l){if(this.fsw._handleError(l))return o(),e}}};Wh.exports=aa});var Qh=v((Kx,ga)=>{"use strict";var ha=require("fs"),ue=require("path"),{promisify:pa}=require("util"),hn;try{hn=require("fsevents")}catch(t){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(t)}if(hn){let t=process.version.match(/v(\d+)\.(\d+)/);if(t&&t[1]&&t[2]){let e=Number.parseInt(t[1],10),n=Number.parseInt(t[2],10);e===8&&n<16&&(hn=void 0)}}var{EV_ADD:la,EV_CHANGE:H0,EV_ADD_DIR:jh,EV_UNLINK:ks,EV_ERROR:B0,STR_DATA:F0,STR_END:U0,FSEVENT_CREATED:q0,FSEVENT_MODIFIED:$0,FSEVENT_DELETED:W0,FSEVENT_MOVED:G0,FSEVENT_UNKNOWN:j0,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:V0,FSEVENT_TYPE_FILE:z0,FSEVENT_TYPE_DIRECTORY:lr,FSEVENT_TYPE_SYMLINK:Jh,ROOT_GLOBSTAR:Vh,DIR_SUFFIX:Y0,DOT_SLASH:zh,FUNCTION_TYPE:ca,EMPTY_FN:K0,IDENTITY_FN:J0}=Is(),Q0=t=>isNaN(t)?{}:{depth:t},da=pa(ha.stat),X0=pa(ha.lstat),Yh=pa(ha.realpath),Z0={stat:da,lstat:X0},Ht=new Map,eb=10,tb=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),nb=(t,e)=>({stop:hn.watch(t,e)});function rb(t,e,n,r){let s=ue.extname(e)?ue.dirname(e):e,i=ue.dirname(s),o=Ht.get(s);sb(i)&&(s=i);let a=ue.resolve(t),l=a!==e,c=(d,f,p)=>{l&&(d=d.replace(e,a)),(d===a||!d.indexOf(a+ue.sep))&&n(d,f,p)},u=!1;for(let d of Ht.keys())if(e.indexOf(ue.resolve(d)+ue.sep)===0){s=d,o=Ht.get(s),u=!0;break}return o||u?o.listeners.add(c):(o={listeners:new Set([c]),rawEmitter:r,watcher:nb(s,(d,f)=>{if(!o.listeners.size||f&V0)return;let p=hn.getInfo(d,f);o.listeners.forEach(g=>{g(d,f,p)}),o.rawEmitter(p.event,d,p)})},Ht.set(s,o)),()=>{let d=o.listeners;if(d.delete(c),!d.size&&(Ht.delete(s),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var sb=t=>{let e=0;for(let n of Ht.keys())if(n.indexOf(t)===0&&(e++,e>=eb))return!0;return!1},ib=()=>hn&&Ht.size<128,ua=(t,e)=>{let n=0;for(;!t.indexOf(e)&&(t=ue.dirname(t))!==e;)n++;return n},Kh=(t,e)=>t.type===lr&&e.isDirectory()||t.type===Jh&&e.isSymbolicLink()||t.type===z0&&e.isFile(),fa=class{constructor(e){this.fsw=e}checkIgnored(e,n){let r=this.fsw._ignoredPaths;if(this.fsw._isIgnored(e,n))return r.add(e),n&&n.isDirectory()&&r.add(e+Vh),!0;r.delete(e),r.delete(e+Vh)}addOrChange(e,n,r,s,i,o,a,l){let c=i.has(o)?H0:la;this.handleEvent(c,e,n,r,s,i,o,a,l)}async checkExists(e,n,r,s,i,o,a,l){try{let c=await da(e);if(this.fsw.closed)return;Kh(a,c)?this.addOrChange(e,n,r,s,i,o,a,l):this.handleEvent(ks,e,n,r,s,i,o,a,l)}catch(c){c.code==="EACCES"?this.addOrChange(e,n,r,s,i,o,a,l):this.handleEvent(ks,e,n,r,s,i,o,a,l)}}handleEvent(e,n,r,s,i,o,a,l,c){if(!(this.fsw.closed||this.checkIgnored(n)))if(e===ks){let u=l.type===lr;(u||o.has(a))&&this.fsw._remove(i,a,u)}else{if(e===la){if(l.type===lr&&this.fsw._getWatchedDir(n),l.type===Jh&&c.followSymlinks){let d=c.depth===void 0?void 0:ua(r,s)+1;return this._addToFsEvents(n,!1,!0,d)}this.fsw._getWatchedDir(i).add(a)}let u=l.type===lr?e+Y0:e;this.fsw._emit(u,n),u===jh&&this._addToFsEvents(n,!1,!0)}}_watchWithFsEvents(e,n,r,s){if(this.fsw.closed||this.fsw._isIgnored(e))return;let i=this.fsw.options,a=rb(e,n,async(l,c,u)=>{if(this.fsw.closed||i.depth!==void 0&&ua(l,n)>i.depth)return;let d=r(ue.join(e,ue.relative(e,l)));if(s&&!s(d))return;let f=ue.dirname(d),p=ue.basename(d),g=this.fsw._getWatchedDir(u.type===lr?d:f);if(tb.has(c)||u.event===j0)if(typeof i.ignored===ca){let h;try{h=await da(d)}catch{}if(this.fsw.closed||this.checkIgnored(d,h))return;Kh(u,h)?this.addOrChange(d,l,n,f,g,p,u,i):this.handleEvent(ks,d,l,n,f,g,p,u,i)}else this.checkExists(d,l,n,f,g,p,u,i);else switch(u.event){case q0:case $0:return this.addOrChange(d,l,n,f,g,p,u,i);case W0:case G0:return this.checkExists(d,l,n,f,g,p,u,i)}},this.fsw._emitRaw);return this.fsw._emitReady(),a}async _handleFsEventsSymlink(e,n,r,s){if(!(this.fsw.closed||this.fsw._symlinkPaths.has(n))){this.fsw._symlinkPaths.set(n,!0),this.fsw._incrReadyCount();try{let i=await Yh(e);if(this.fsw.closed)return;if(this.fsw._isIgnored(i))return this.fsw._emitReady();this.fsw._incrReadyCount(),this._addToFsEvents(i||e,o=>{let a=e;return i&&i!==zh?a=o.replace(i,e):o!==zh&&(a=ue.join(e,o)),r(a)},!1,s)}catch(i){if(this.fsw._handleError(i))return this.fsw._emitReady()}}}emitAdd(e,n,r,s,i){let o=r(e),a=n.isDirectory(),l=this.fsw._getWatchedDir(ue.dirname(o)),c=ue.basename(o);a&&this.fsw._getWatchedDir(o),!l.has(c)&&(l.add(c),(!s.ignoreInitial||i===!0)&&this.fsw._emit(a?jh:la,o,n))}initWatch(e,n,r,s){if(this.fsw.closed)return;let i=this._watchWithFsEvents(r.watchPath,ue.resolve(e||r.watchPath),s,r.globFilter);this.fsw._addPathCloser(n,i)}async _addToFsEvents(e,n,r,s){if(this.fsw.closed)return;let i=this.fsw.options,o=typeof n===ca?n:J0,a=this.fsw._getWatchHelpers(e);try{let l=await Z0[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))throw null;if(l.isDirectory()){if(a.globFilter||this.emitAdd(o(e),l,o,i,r),s&&s>i.depth)return;this.fsw._readdirp(a.watchPath,{fileFilter:c=>a.filterPath(c),directoryFilter:c=>a.filterDir(c),...Q0(i.depth-(s||0))}).on(F0,c=>{if(this.fsw.closed||c.stats.isDirectory()&&!a.filterPath(c))return;let u=ue.join(a.watchPath,c.path),{fullPath:d}=c;if(a.followSymlinks&&c.stats.isSymbolicLink()){let f=i.depth===void 0?void 0:ua(u,ue.resolve(a.watchPath))+1;this._handleFsEventsSymlink(u,d,o,f)}else this.emitAdd(u,c.stats,o,i,r)}).on(B0,K0).on(U0,()=>{this.fsw._emitReady()})}else this.emitAdd(a.watchPath,l,o,i,r),this.fsw._emitReady()}catch(l){(!l||this.fsw._handleError(l))&&(this.fsw._emitReady(),this.fsw._emitReady())}if(i.persistent&&r!==!0)if(typeof n===ca)this.initWatch(void 0,e,a,o);else{let l;try{l=await Yh(a.watchPath)}catch{}this.initWatch(l,e,a,o)}}};ga.exports=fa;ga.exports.canUse=ib});var lp=v(ka=>{"use strict";var{EventEmitter:ob}=require("events"),Ta=require("fs"),F=require("path"),{promisify:sp}=require("util"),ab=Bf(),wa=jf().default,lb=Qf(),ma=Ko(),cb=Lh(),ub=zo(),db=Gh(),Xh=Qh(),{EV_ALL:ya,EV_READY:fb,EV_ADD:Ps,EV_CHANGE:cr,EV_UNLINK:Zh,EV_ADD_DIR:hb,EV_UNLINK_DIR:pb,EV_RAW:gb,EV_ERROR:_a,STR_CLOSE:mb,STR_END:yb,BACK_SLASH_RE:_b,DOUBLE_SLASH_RE:ep,SLASH_OR_BACK_SLASH_RE:Sb,DOT_RE:vb,REPLACER_RE:wb,SLASH:Sa,SLASH_SLASH:bb,BRACE_START:Ab,BANG:ba,ONE_DOT:ip,TWO_DOTS:Eb,GLOBSTAR:Ib,SLASH_GLOBSTAR:va,ANYMATCH_OPTS:Aa,STRING_TYPE:Ra,FUNCTION_TYPE:xb,EMPTY_STR:Ea,EMPTY_FN:Cb,isWindows:Tb,isMacos:Rb,isIBMi:kb}=Is(),Pb=sp(Ta.stat),Mb=sp(Ta.readdir),Ia=(t=[])=>Array.isArray(t)?t:[t],op=(t,e=[])=>(t.forEach(n=>{Array.isArray(n)?op(n,e):e.push(n)}),e),tp=t=>{let e=op(Ia(t));if(!e.every(n=>typeof n===Ra))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(ap)},np=t=>{let e=t.replace(_b,Sa),n=!1;for(e.startsWith(bb)&&(n=!0);e.match(ep);)e=e.replace(ep,Sa);return n&&(e=Sa+e),e},ap=t=>np(F.normalize(np(t))),rp=(t=Ea)=>e=>typeof e!==Ra?e:ap(F.isAbsolute(e)?e:F.join(t,e)),Lb=(t,e)=>F.isAbsolute(t)?t:t.startsWith(ba)?ba+F.join(e,t.slice(1)):F.join(e,t),Oe=(t,e)=>t[e]===void 0,xa=class{constructor(e,n){this.path=e,this._removeWatcher=n,this.items=new Set}add(e){let{items:n}=this;n&&e!==ip&&e!==Eb&&n.add(e)}async remove(e){let{items:n}=this;if(!n||(n.delete(e),n.size>0))return;let r=this.path;try{await Mb(r)}catch{this._removeWatcher&&this._removeWatcher(F.dirname(r),F.basename(r))}}has(e){let{items:n}=this;if(n)return n.has(e)}getChildren(){let{items:e}=this;if(e)return[...e.values()]}dispose(){this.items.clear(),delete this.path,delete this._removeWatcher,delete this.items,Object.freeze(this)}},Nb="stat",Ob="lstat",Ca=class{constructor(e,n,r,s){this.fsw=s,this.path=e=e.replace(wb,Ea),this.watchPath=n,this.fullWatchPath=F.resolve(n),this.hasGlob=n!==e,e===Ea&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&r?void 0:!1,this.globFilter=this.hasGlob?wa(e,void 0,Aa):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=r,this.statMethod=r?Nb:Ob}checkGlobSymlink(e){return this.globSymlink===void 0&&(this.globSymlink=e.fullParentDir===this.fullWatchPath?!1:{realPath:e.fullParentDir,linkPath:this.fullWatchPath}),this.globSymlink?e.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath):e.fullPath}entryPath(e){return F.join(this.watchPath,F.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){let{stats:n}=e;if(n&&n.isSymbolicLink())return this.filterDir(e);let r=this.entryPath(e);return(this.hasGlob&&typeof this.globFilter===xb?this.globFilter(r):!0)&&this.fsw._isntIgnored(r,n)&&this.fsw._hasReadPermissions(n)}getDirParts(e){if(!this.hasGlob)return[];let n=[];return(e.includes(Ab)?cb.expand(e):[e]).forEach(s=>{n.push(F.relative(this.watchPath,s).split(Sb))}),n}filterDir(e){if(this.hasGlob){let n=this.getDirParts(this.checkGlobSymlink(e)),r=!1;this.unmatchedGlob=!this.dirParts.some(s=>s.every((i,o)=>(i===Ib&&(r=!0),r||!n[0][o]||wa(i,n[0][o],Aa))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Ms=class extends ob{constructor(e){super();let n={};e&&Object.assign(n,e),this._watched=new Map,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._symlinkPaths=new Map,this._streams=new Set,this.closed=!1,Oe(n,"persistent")&&(n.persistent=!0),Oe(n,"ignoreInitial")&&(n.ignoreInitial=!1),Oe(n,"ignorePermissionErrors")&&(n.ignorePermissionErrors=!1),Oe(n,"interval")&&(n.interval=100),Oe(n,"binaryInterval")&&(n.binaryInterval=300),Oe(n,"disableGlobbing")&&(n.disableGlobbing=!1),n.enableBinaryInterval=n.binaryInterval!==n.interval,Oe(n,"useFsEvents")&&(n.useFsEvents=!n.usePolling),Xh.canUse()||(n.useFsEvents=!1),Oe(n,"usePolling")&&!n.useFsEvents&&(n.usePolling=Rb),kb&&(n.usePolling=!0);let s=process.env.CHOKIDAR_USEPOLLING;if(s!==void 0){let l=s.toLowerCase();l==="false"||l==="0"?n.usePolling=!1:l==="true"||l==="1"?n.usePolling=!0:n.usePolling=!!l}let i=process.env.CHOKIDAR_INTERVAL;i&&(n.interval=Number.parseInt(i,10)),Oe(n,"atomic")&&(n.atomic=!n.usePolling&&!n.useFsEvents),n.atomic&&(this._pendingUnlinks=new Map),Oe(n,"followSymlinks")&&(n.followSymlinks=!0),Oe(n,"awaitWriteFinish")&&(n.awaitWriteFinish=!1),n.awaitWriteFinish===!0&&(n.awaitWriteFinish={});let o=n.awaitWriteFinish;o&&(o.stabilityThreshold||(o.stabilityThreshold=2e3),o.pollInterval||(o.pollInterval=100),this._pendingWrites=new Map),n.ignored&&(n.ignored=Ia(n.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Cb,this._readyEmitted=!0,process.nextTick(()=>this.emit(fb)))},this._emitRaw=(...l)=>this.emit(gb,...l),this._readyEmitted=!1,this.options=n,n.useFsEvents?this._fsEventsHandler=new Xh(this):this._nodeFsHandler=new db(this),Object.freeze(n)}add(e,n,r){let{cwd:s,disableGlobbing:i}=this.options;this.closed=!1;let o=tp(e);return s&&(o=o.map(a=>{let l=Lb(a,s);return i||!ma(a)?l:ub(l)})),o=o.filter(a=>a.startsWith(ba)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+va),this._userIgnored=void 0,!0)),this.options.useFsEvents&&this._fsEventsHandler?(this._readyCount||(this._readyCount=o.length),this.options.persistent&&(this._readyCount+=o.length),o.forEach(a=>this._fsEventsHandler._addToFsEvents(a))):(this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let l=await this._nodeFsHandler._addToNodeFs(a,!r,0,0,n);return l&&this._emitReady(),l})).then(a=>{this.closed||a.filter(l=>l).forEach(l=>{this.add(F.dirname(l),F.basename(n||l))})})),this}unwatch(e){if(this.closed)return this;let n=tp(e),{cwd:r}=this.options;return n.forEach(s=>{!F.isAbsolute(s)&&!this._closers.has(s)&&(r&&(s=F.join(r,s)),s=F.resolve(s)),this._closePath(s),this._ignoredPaths.add(s),this._watched.has(s)&&this._ignoredPaths.add(s+va),this._userIgnored=void 0}),this}close(){if(this.closed)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(n=>n.forEach(r=>{let s=r();s instanceof Promise&&e.push(s)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),["closers","watched","streams","symlinkPaths","throttled"].forEach(n=>{this[`_${n}`].clear()}),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((n,r)=>{let s=this.options.cwd?F.relative(this.options.cwd,r):r;e[s||ip]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(...n),e!==_a&&this.emit(ya,...n)}async _emit(e,n,r,s,i){if(this.closed)return;let o=this.options;Tb&&(n=F.normalize(n)),o.cwd&&(n=F.relative(o.cwd,n));let a=[e,n];i!==void 0?a.push(r,s,i):s!==void 0?a.push(r,s):r!==void 0&&a.push(r);let l=o.awaitWriteFinish,c;if(l&&(c=this._pendingWrites.get(n)))return c.lastChange=new Date,this;if(o.atomic){if(e===Zh)return this._pendingUnlinks.set(n,a),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(ya,...u),this._pendingUnlinks.delete(d)})},typeof o.atomic=="number"?o.atomic:100),this;e===Ps&&this._pendingUnlinks.has(n)&&(e=a[0]=cr,this._pendingUnlinks.delete(n))}if(l&&(e===Ps||e===cr)&&this._readyEmitted){let u=(d,f)=>{d?(e=a[0]=_a,a[1]=d,this.emitWithAll(e,a)):f&&(a.length>2?a[2]=f:a.push(f),this.emitWithAll(e,a))};return this._awaitWriteFinish(n,l.stabilityThreshold,e,u),this}if(e===cr&&!this._throttle(cr,n,50))return this;if(o.alwaysStat&&r===void 0&&(e===Ps||e===hb||e===cr)){let u=o.cwd?F.join(o.cwd,n):n,d;try{d=await Pb(u)}catch{}if(!d||this.closed)return;a.push(d)}return this.emitWithAll(e,a),this}_handleError(e){let n=e&&e.code;return e&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(_a,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e),i=s.get(n);if(i)return i.count++,!1;let o,a=()=>{let c=s.get(n),u=c?c.count:0;return s.delete(n),clearTimeout(o),c&&clearTimeout(c.timeoutObject),u};o=setTimeout(a,r);let l={timeoutObject:o,clear:a,count:0};return s.set(n,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,s){let i,o=e;this.options.cwd&&!F.isAbsolute(e)&&(o=F.join(this.options.cwd,e));let a=new Date,l=c=>{Ta.stat(o,(u,d)=>{if(u||!this._pendingWrites.has(e)){u&&u.code!=="ENOENT"&&s(u);return}let f=Number(new Date);c&&d.size!==c.size&&(this._pendingWrites.get(e).lastChange=f);let p=this._pendingWrites.get(e);f-p.lastChange>=n?(this._pendingWrites.delete(e),s(void 0,d)):i=setTimeout(l,this.options.awaitWriteFinish.pollInterval,d)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(i),r)}),i=setTimeout(l,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,n){if(this.options.atomic&&vb.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,s=this.options.ignored,i=s&&s.map(rp(r)),o=Ia(i).filter(l=>typeof l===Ra&&!ma(l)).map(l=>l+va),a=this._getGlobIgnored().map(rp(r)).concat(i,o);this._userIgnored=wa(a,void 0,Aa)}return this._userIgnored([e,n])}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e,n){let r=n||this.options.disableGlobbing||!ma(e)?e:lb(e),s=this.options.followSymlinks;return new Ca(e,r,s,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let n=F.resolve(e);return this._watched.has(n)||this._watched.set(n,new xa(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){if(this.options.ignorePermissionErrors)return!0;let r=(e&&Number.parseInt(e.mode,10))&511;return!!(4&Number.parseInt(r.toString(8)[0],10))}_remove(e,n,r){let s=F.join(e,n),i=F.resolve(s);if(r=r??(this._watched.has(s)||this._watched.has(i)),!this._throttle("remove",s,100))return;!r&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(s).getChildren().forEach(f=>this._remove(s,f));let l=this._getWatchedDir(e),c=l.has(n);l.remove(n),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let u=s;if(this.options.cwd&&(u=F.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===Ps)return;this._watched.delete(s),this._watched.delete(i);let d=r?pb:Zh;c&&!this._isIgnored(s)&&this._emit(d,s),this.options.useFsEvents||this._closePath(s)}_closePath(e){this._closeFile(e);let n=F.dirname(e);this._getWatchedDir(n).remove(F.basename(e))}_closeFile(e){let n=this._closers.get(e);n&&(n.forEach(r=>r()),this._closers.delete(e))}_addPathCloser(e,n){if(!n)return;let r=this._closers.get(e);r||(r=[],this._closers.set(e,r)),r.push(n)}_readdirp(e,n){if(this.closed)return;let r={type:ya,alwaysStat:!0,lstat:!0,...n},s=ab(e,r);return this._streams.add(s),s.once(mb,()=>{s=void 0}),s.once(yb,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};ka.FSWatcher=Ms;var Db=(t,e)=>{let n=new Ms(e);return n.add(t),n};ka.watch=Db});var bg=require("http");var ty=St(nc(),1),ny=St(pi(),1),ry=St(yi(),1),sy=St(Br(),1),Ii=St(dc(),1);var Me=require("fs/promises"),Ag=require("crypto"),wr=require("path"),Eg=require("os"),ol=St(vd(),1);var Mt=require("child_process"),Ld=require("fs"),Z=require("path"),Vn=require("os");var as=require("fs");var wd=require("os"),he=require("path"),Xe=(0,he.join)((0,wd.homedir)(),".vibelet"),es=(0,he.join)(Xe,"logs"),ts=(0,he.join)(Xe,"data"),vS=(0,he.join)(Xe,"runtime"),jI=(0,he.join)(vS,"current"),bd=(0,he.join)(Xe,"identity.json"),Ad=(0,he.join)(Xe,"pairings.json"),Ed=(0,he.join)(ts,"push-subscriptions.json"),ns=(0,he.join)(ts,"sessions.json"),rn=(0,he.join)(ts,"audit.jsonl"),yo=(0,he.join)(ts,"uploads"),rs=(0,he.join)(es,"daemon.stdout.log"),ss=(0,he.join)(es,"daemon.stderr.log"),Id=(0,he.join)(Xe,"update-check.json"),_o=(0,he.join)(Xe,"pairing-qr.png");var is={stdout:!1,stderr:!1};function xd(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function wS(t){return!t.destroyed&&t.writable!==!1}function Cd(t,e){if(is[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!wS(n))return is[t]=!0,!1;try{return n.write(e,r=>{xd(r)&&(is[t]=!0)}),!0}catch(r){return xd(r)&&(is[t]=!0),!1}}function sn(t){return Cd("stdout",t)}function os(t){return Cd("stderr",t)}var Td={debug:10,info:20,warn:30,error:40},bS=process.env.VIBE_LOG_LEVEL||"info";function AS(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function ES(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var kd=!AS()&&!ES();if(kd)try{(0,as.mkdirSync)(es,{recursive:!0})}catch{}function Rd(t,e,n){if(Td[t]<Td[bS])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},s=JSON.stringify(r);if(t==="error"||t==="warn"?os(s+`
22
- `):sn(s+`
23
- `),kd){let i=t==="error"||t==="warn"?ss:rs;try{(0,as.appendFileSync)(i,s+`
24
- `)}catch{}}}function Pd(t={}){function e(n,r,s){typeof r=="string"?Rd(n,t,r):Rd(n,{...t,...r},s)}return{debug:(n,r)=>e("debug",n,r),info:(n,r)=>e("info",n,r),warn:(n,r)=>e("warn",n,r),error:(n,r)=>e("error",n,r),child:n=>Pd({...t,...n})}}var K=Pd({module:"daemon"});var IS=["fnm_multishells"],xS=6e4,pt=process.platform==="win32",CS=K.child({module:"config"});function ht(t){return IS.some(e=>t.includes(e))}function wo(){return pt?[]:[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var on=null;function Nd(){if(on&&!ht(on.PATH??""))return on;for(let t of wo())try{let e=(0,Mt.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let r of e.split(`
25
- `)){let s=r.indexOf("=");s>0&&(n[r.slice(0,s)]=r.slice(s+1))}return ht(n.PATH??"")?on=null:on=n,n}catch{}return on={},{}}function TS(t=Nd()){let e=(0,Vn.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(pt?(0,Z.join)(e,"pnpm"):(0,Z.join)(e,"Library","pnpm")),r=t.PATH||process.env.PATH||"",s=pt?[(0,Z.join)(e,".npm-global","bin"),(0,Z.join)(e,".local","bin"),(0,Z.join)(e,".claude","bin"),n,(0,Z.join)(e,"AppData","Roaming","npm"),(0,Z.join)(e,"AppData","Local","Programs","node")]:["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,Z.join)(e,".npm-global","bin"),(0,Z.join)(e,".local","bin"),(0,Z.join)(e,".claude","bin"),n],i=r.split(Z.delimiter).filter(Boolean),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(Z.delimiter)}function So(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?Math.floor(r):e}function vo(t,e){let n=process.env[t];if(n==null||n==="")return e;let r=Number(n);return Number.isFinite(r)&&r>=0?Math.floor(r):e}function Lt(){let t=Nd(),e={};for(let[n,r]of Object.entries(process.env))typeof r=="string"&&(e[n]=r);for(let[n,r]of Object.entries(t))typeof r=="string"&&(e[n]=r);return e.PATH=TS(t),e.HOME||(e.HOME=(0,Vn.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function bo(t){if(pt)try{let n=(0,Mt.execFileSync)("where.exe",[t],{timeout:3e3,stdio:"pipe",encoding:"utf-8"}).trim().split(/\r?\n/).filter(Boolean);return n.find(s=>s.endsWith(".exe"))??n[0]}catch{return}}function Pt(t,e=3e3){try{return(0,Mt.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:Lt(),...pt?{shell:!0}:{}}).trim()||null}catch{return null}}function RS(t){for(let e of wo())try{let n=(0,Mt.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function kS(){let t=(0,Vn.homedir)();return[(0,Z.join)(t,".local","bin","claude"),(0,Z.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,Z.join)(t,".npm-global","bin","claude")]}function PS(){if(pt){let t=bo("claude");return t&&Pt(t)?t:void 0}for(let t of kS())if(Pt(t))return t;try{let t=(0,Mt.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Lt()}).trim();if(t&&!t.includes("cmux")&&Pt(t))return t}catch{}}function MS(){let t=(0,Vn.homedir)(),e=[process.env.PNPM_HOME,(0,Z.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,Z.join)(t,".npm-global","bin","codex"),(0,Z.join)(t,".local","bin","codex"),...e.map(n=>(0,Z.join)(n,"codex"))]}function LS(){if(pt){let n=bo("codex");return n&&Pt(n)?n:void 0}let t;for(let n of MS())if(Pt(n)){if(!ht(n))return n;t=n}try{let n=(0,Mt.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Lt()}).trim();if(n&&Pt(n)){if(!ht(n))return n;t=t??n}}catch{}let e=RS("codex");if(e&&Pt(e)){if(!ht(e))return e;t=t??e}return t}function Od(t,e){let n=null,r=0;return()=>{let s=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[s])return process.env[s];let i=Date.now();if(!n||i-r>xS||!(0,Ld.existsSync)(n)||ht(n)){let o=t();n=o??e,r=i,CS.info({name:e,path:n,transient:ht(n),isBare:o==null},"binary resolved")}return n}}var NS=Od(PS,"claude"),OS=Od(LS,"codex");function DS(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("--")&&n+1<e.length){let s=r.slice(2);t[s]=e[++n]}}return t}var Md=DS();function HS(t,e){return pt?{command:bo(t)??t,args:e}:{command:wo()[0]??"/bin/zsh",args:["-lc",`command -v ${t} >/dev/null 2>&1 && exec ${t} "$@"`,"--",...e]}}var C={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:Md.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:Md["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:vo("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:vo("VIBE_TURN_STALL_TIMEOUT_MS",300*1e3),auditMaxBytes:So("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:So("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:So("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),pairWindowMs:vo("VIBE_PAIR_WINDOW_MS",300*1e3),pairReusable:process.env.VIBE_PAIR_REUSABLE==="1",get claudePath(){return NS()},get codexPath(){return OS()},isTransientPath:ht,execViaLoginShell:HS,buildSanitizedEnv:Lt};var Ka=require("crypto"),ng=require("fs/promises");var Gd=require("child_process"),jd=require("fs");var ls=require("fs"),Bd=require("path");var ye=require("fs");function BS(t,e,n,r){let s=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,s,r??i))}function zn(t,e){if(!(0,ye.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,ye.statSync)(t).size,s=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||r+s<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:r,afterBytes:r,reclaimedBytes:0};let i=BS(r,e.maxBytes,s,e.retainBytes),o=(0,ye.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,ye.readSync)(o,l,0,i,r-i);let c=0;if(r>i){let u=l.indexOf(10);u>=0&&u+1<l.length&&(c=u+1)}a=l.subarray(c)}return(0,ye.ftruncateSync)(o,0),a.length>0&&(0,ye.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,ye.closeSync)(o)}}function Dd(t){let e=[zn(t.auditPath,{maxBytes:t.auditMaxBytes}),zn(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),zn(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,r)=>n+r.reclaimedBytes,0)}}var Hd=!1,FS=new Set(["ts","event","source","appEvent","level"]);function US(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function qS(t={}){let e={};for(let[n,r]of Object.entries(t))FS.has(n)||(e[n]=r);return e}function $S(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...qS(n)}}function WS(){Hd||((0,ls.mkdirSync)((0,Bd.dirname)(rn),{recursive:!0}),Hd=!0)}var Ao=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},s){this.write($S(e,n,r,s))}write(e){if(!US()){WS();try{let n=JSON.stringify(e)+`
26
- `;zn(rn,{maxBytes:C.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,ls.appendFileSync)(rn,n)}catch{}}}},k=new Ao;var gt=require("fs"),Fd=require("os"),Yn=require("path"),Ud=require("crypto"),Eo="claude-hook:",Kn="x-vibelet-claude-hook-secret",Jn={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function GS(t,e){return`#!/usr/bin/env node
18
+ `,typeof n=="function"&&n(null,a),a}});var Ul=y(Fl=>{var Hh="\x1B[47m",Fh="\x1B[40m",Fs="\x1B[37m",Us="\x1B[30m",Ye="\x1B[0m",Uh=Hh+Us,qh=Fh+Fs,Wh=function(t,e,n){return{"00":Ye+" "+t,"01":Ye+e+"\u2584"+t,"02":Ye+n+"\u2584"+t,10:Ye+e+"\u2580"+t,11:" ",12:"\u2584",20:Ye+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},Dl=function(t,e,n,r){let s=e+1;if(n>=s||r>=s||r<-1||n<-1)return"0";if(n>=e||r>=e||r<0||n<0)return"1";let i=r*e+n;return t[i]?"2":"1"},Hl=function(t,e,n,r){return Dl(t,e,n,r)+Dl(t,e,n,r+1)};Fl.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?qh:Uh,c=Wh(o,i?Us:Fs,i?Fs:Us),u=Ye+`
19
+ `+o,d=o;for(let f=-1;f<r+1;f+=2){for(let h=-1;h<r;h++)d+=c[Hl(s,r,h,f)];d+=c[Hl(s,r,r,f)]+u}return d+=Ye,typeof n=="function"&&n(null,d),d}});var Wl=y(ql=>{var Gh=Bl(),jh=Ul();ql.render=function(t,e,n){return e&&e.small?jh.render(t,e,n):Gh.render(t,e,n)}});var Ws=y(jl=>{var Vh=Xt();function Gl(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function qs(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function $h(t,e,n){let r="",s=0,i=!1,o=0;for(let a=0;a<t.length;a++){let l=Math.floor(a%e),c=Math.floor(a/e);!l&&!i&&(i=!0),t[a]?(o++,a>0&&l>0&&t[a-1]||(r+=i?qs("M",l+n,.5+c+n):qs("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=qs("h",o),o=0)):s++}return r}jl.render=function(e,n,r){let s=Vh.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+Gl(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+Gl(s.color.dark,"stroke")+' d="'+$h(o,i,s.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',f='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
20
+ `;return typeof r=="function"&&r(null,f),f}});var Vl=y(Jn=>{var zh=Ws();Jn.render=zh.render;Jn.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),a='<?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">'+Jn.render(n,r);i.writeFile(e,a,s)}});var $l=y(Kn=>{var Gs=Xt();function Yh(t,e,n){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=n,e.width=n,e.style.height=n+"px",e.style.width=n+"px"}function Jh(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Kn.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=Jh()),s=Gs.getOptions(s);let o=Gs.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return Gs.qrToImageData(l.data,e,s),Yh(a,i,o),a.putImageData(l,0,0),i};Kn.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=Kn.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var Yl=y(Zt=>{var Kh=rs(),js=ws(),zl=$l(),Qh=Ws();function Vs(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!Kh())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=n,n=e,e=r=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=n,n=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(n=e,e=r=void 0):o===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(l,c){try{let u=js.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=js.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}Zt.create=js.create;Zt.toCanvas=Vs.bind(null,zl.render);Zt.toDataURL=Vs.bind(null,zl.renderToDataURL);Zt.toString=Vs.bind(null,function(t,e,n){return Qh.render(t,n)})});var Xl=y(Re=>{var Jl=rs(),$s=ws(),Xh=Ll(),Kl=Nl(),Zh=Wl(),Ql=Vl();function en(t,e,n){if(typeof t>"u")throw new Error("String required as first argument");if(typeof n>"u"&&(n=e,e={}),typeof n!="function")if(Jl())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function eg(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Qn(t){switch(t){case"svg":return Ql;case"txt":case"utf8":return Kl;case"png":case"image/png":default:return Xh}}function tg(t){switch(t){case"svg":return Ql;case"terminal":return Zh;case"utf8":default:return Kl}}function tn(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=$s.create(e,n.opts);return t(i,n.opts,function(o,a){return o?s(o):r(a)})}catch(i){s(i)}});try{let r=$s.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}Re.create=$s.create;Re.toCanvas=Yl().toCanvas;Re.toString=function(e,n,r){let s=en(e,n,r),i=s.opts?s.opts.type:void 0,o=tg(i);return tn(o.render,e,s)};Re.toDataURL=function(e,n,r){let s=en(e,n,r),i=Qn(s.opts.type);return tn(i.renderToDataURL,e,s)};Re.toBuffer=function(e,n,r){let s=en(e,n,r),i=Qn(s.opts.type);return tn(i.renderToBuffer,e,s)};Re.toFile=function(e,n,r,s){if(typeof e!="string"||!(typeof n=="string"||typeof n=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!Jl())throw new Error("Too few arguments provided");let i=en(n,r,s),o=i.opts.type||eg(e),l=Qn(o).renderToFile.bind(null,e);return tn(l,n,i)};Re.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=en(n,r,e.emit.bind(e,"error")),o=Qn("png").renderToFileStream.bind(null,e);tn(o,n,s)}});var ec=y((mS,Zl)=>{Zl.exports=Xl()});var sd=require("http");var Df=rt(Bo(),1),Hf=rt(Vr(),1),Ff=rt(Yr(),1),Uf=rt(Bn(),1),ns=rt(Vo(),1);var re=require("fs/promises"),id=require("crypto"),In=require("path"),od=require("os"),Fi=rt(ec(),1);var Ke=require("child_process"),pc=require("fs"),L=require("path"),nn=require("os");var ir=require("fs");var tc=require("os"),G=require("path"),_e=(0,G.join)((0,tc.homedir)(),".vibelet"),Xn=(0,G.join)(_e,"logs"),Zn=(0,G.join)(_e,"data"),ng=(0,G.join)(_e,"runtime"),yS=(0,G.join)(ng,"current"),nc=(0,G.join)(_e,"identity.json"),rc=(0,G.join)(_e,"pairings.json"),sc=(0,G.join)(Zn,"push-subscriptions.json"),er=(0,G.join)(Zn,"sessions.json"),St=(0,G.join)(Zn,"audit.jsonl"),zs=(0,G.join)(Zn,"uploads"),tr=(0,G.join)(Xn,"daemon.stdout.log"),nr=(0,G.join)(Xn,"daemon.stderr.log"),ic=(0,G.join)(_e,"update-check.json"),Ys=(0,G.join)(_e,"pairing-qr.png");var rr={stdout:!1,stderr:!1};function oc(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function rg(t){return!t.destroyed&&t.writable!==!1}function ac(t,e){if(rr[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!rg(n))return rr[t]=!0,!1;try{return n.write(e,r=>{oc(r)&&(rr[t]=!0)}),!0}catch(r){return oc(r)&&(rr[t]=!0),!1}}function _t(t){return ac("stdout",t)}function sr(t){return ac("stderr",t)}var lc={debug:10,info:20,warn:30,error:40},sg=process.env.VIBE_LOG_LEVEL||"info";function ig(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function og(){try{let{fstatSync:t}=require("fs");return t(1).isFile()}catch{return!1}}var uc=!ig()&&!og();if(uc)try{(0,ir.mkdirSync)(Xn,{recursive:!0})}catch{}function cc(t,e,n){if(lc[t]<lc[sg])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},s=JSON.stringify(r);if(t==="error"||t==="warn"?sr(s+`
21
+ `):_t(s+`
22
+ `),uc){let i=t==="error"||t==="warn"?nr:tr;try{(0,ir.appendFileSync)(i,s+`
23
+ `)}catch{}}}function dc(t={}){function e(n,r,s){typeof r=="string"?cc(n,t,r):cc(n,{...t,...r},s)}return{debug:(n,r)=>e("debug",n,r),info:(n,r)=>e("info",n,r),warn:(n,r)=>e("warn",n,r),error:(n,r)=>e("error",n,r),child:n=>dc({...t,...n})}}var P=dc({module:"daemon"});var ag=["fnm_multishells"],lg=6e4,Le=process.platform==="win32",cg=P.child({module:"config"});function Me(t){return ag.some(e=>t.includes(e))}function Qs(){return Le?[]:[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var bt=null;function hc(){if(bt&&!Me(bt.PATH??""))return bt;for(let t of Qs())try{let e=(0,Ke.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),n={};for(let r of e.split(`
24
+ `)){let s=r.indexOf("=");s>0&&(n[r.slice(0,s)]=r.slice(s+1))}return Me(n.PATH??"")?bt=null:bt=n,n}catch{}return bt={},{}}function ug(t=hc()){let e=(0,nn.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(Le?(0,L.join)(e,"pnpm"):(0,L.join)(e,"Library","pnpm")),r=t.PATH||process.env.PATH||"",s=Le?[(0,L.join)(e,".npm-global","bin"),(0,L.join)(e,".local","bin"),(0,L.join)(e,".claude","bin"),n,(0,L.join)(e,"AppData","Roaming","npm"),(0,L.join)(e,"AppData","Local","Programs","node")]:["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,L.join)(e,".npm-global","bin"),(0,L.join)(e,".local","bin"),(0,L.join)(e,".claude","bin"),n],i=r.split(L.delimiter).filter(Boolean),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(L.delimiter)}function Js(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?Math.floor(r):e}function Ks(t,e){let n=process.env[t];if(n==null||n==="")return e;let r=Number(n);return Number.isFinite(r)&&r>=0?Math.floor(r):e}function Qe(){let t=hc(),e={};for(let[n,r]of Object.entries(process.env))typeof r=="string"&&(e[n]=r);for(let[n,r]of Object.entries(t))typeof r=="string"&&(e[n]=r);return e.PATH=ug(t),e.HOME||(e.HOME=(0,nn.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Xs(t){if(Le)try{let n=(0,Ke.execFileSync)("where.exe",[t],{timeout:3e3,stdio:"pipe",encoding:"utf-8"}).trim().split(/\r?\n/).filter(Boolean);return n.find(s=>s.endsWith(".exe"))??n[0]}catch{return}}function Je(t,e=3e3){try{return(0,Ke.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:Qe(),...Le?{shell:!0}:{}}).trim()||null}catch{return null}}function dg(t){for(let e of Qs())try{let n=(0,Ke.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function fg(){let t=(0,nn.homedir)();return[(0,L.join)(t,".local","bin","claude"),(0,L.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,L.join)(t,".npm-global","bin","claude")]}function pg(){if(Le){let t=Xs("claude");return t&&Je(t)?t:void 0}for(let t of fg())if(Je(t))return t;try{let t=(0,Ke.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Qe()}).trim();if(t&&!t.includes("cmux")&&Je(t))return t}catch{}}function hg(){let t=(0,nn.homedir)(),e=[process.env.PNPM_HOME,(0,L.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,L.join)(t,".npm-global","bin","codex"),(0,L.join)(t,".local","bin","codex"),...e.map(n=>(0,L.join)(n,"codex"))]}function gg(){if(Le){let n=Xs("codex");return n&&Je(n)?n:void 0}let t;for(let n of hg())if(Je(n)){if(!Me(n))return n;t=n}try{let n=(0,Ke.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Qe()}).trim();if(n&&Je(n)){if(!Me(n))return n;t=t??n}}catch{}let e=dg("codex");if(e&&Je(e)){if(!Me(e))return e;t=t??e}return t}function gc(t,e){let n=null,r=0;return()=>{let s=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[s])return process.env[s];let i=Date.now();if(!n||i-r>lg||!(0,pc.existsSync)(n)||Me(n)){let o=t();n=o??e,r=i,cg.info({name:e,path:n,transient:Me(n),isBare:o==null},"binary resolved")}return n}}var mg=gc(pg,"claude"),yg=gc(gg,"codex");function vg(){let t={},e=process.argv.slice(2);for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith("--")&&n+1<e.length){let s=r.slice(2);t[s]=e[++n]}}return t}var fc=vg();function Sg(t,e){return Le?{command:Xs(t)??t,args:e}:{command:Qs()[0]??"/bin/zsh",args:["-lc",`command -v ${t} >/dev/null 2>&1 && exec ${t} "$@"`,"--",...e]}}var S={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:fc.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:fc["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:Ks("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:Ks("VIBE_TURN_STALL_TIMEOUT_MS",300*1e3),auditMaxBytes:Js("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:Js("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:Js("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),pairWindowMs:Ks("VIBE_PAIR_WINDOW_MS",300*1e3),pairReusable:process.env.VIBE_PAIR_REUSABLE==="1",get claudePath(){return mg()},get codexPath(){return yg()},isTransientPath:Me,execViaLoginShell:Sg,buildSanitizedEnv:Qe};var ki=require("crypto"),Hu=require("fs/promises");var Ac=require("child_process"),Tc=require("fs");var or=require("fs"),vc=require("path");var V=require("fs");function _g(t,e,n,r){let s=Math.max(0,e-n),i=Math.floor(e*.75);return Math.max(0,Math.min(t,s,r??i))}function rn(t,e){if(!(0,V.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,V.statSync)(t).size,s=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||r+s<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:r,afterBytes:r,reclaimedBytes:0};let i=_g(r,e.maxBytes,s,e.retainBytes),o=(0,V.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,V.readSync)(o,l,0,i,r-i);let c=0;if(r>i){let u=l.indexOf(10);u>=0&&u+1<l.length&&(c=u+1)}a=l.subarray(c)}return(0,V.ftruncateSync)(o,0),a.length>0&&(0,V.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,V.closeSync)(o)}}function mc(t){let e=[rn(t.auditPath,{maxBytes:t.auditMaxBytes}),rn(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),rn(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(n=>n.trimmed).length,reclaimedBytes:e.reduce((n,r)=>n+r.reclaimedBytes,0)}}var yc=!1,bg=new Set(["ts","event","source","appEvent","level"]);function wg(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Ig(t={}){let e={};for(let[n,r]of Object.entries(t))bg.has(n)||(e[n]=r);return e}function Ag(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...Ig(n)}}function Tg(){yc||((0,or.mkdirSync)((0,vc.dirname)(St),{recursive:!0}),yc=!0)}var Zs=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},s){this.write(Ag(e,n,r,s))}write(e){if(!wg()){Tg();try{let n=JSON.stringify(e)+`
25
+ `;rn(St,{maxBytes:S.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,or.appendFileSync)(St,n)}catch{}}}},I=new Zs;var Ne=require("fs"),Sc=require("os"),sn=require("path"),_c=require("crypto"),ei="claude-hook:",on="x-vibelet-claude-hook-secret",an={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function xg(t,e){return`#!/usr/bin/env node
27
26
  const http = require('http');
28
27
  const chunks = [];
29
28
  process.stdin.on('data', (chunk) => chunks.push(chunk));
@@ -37,16 +36,16 @@ process.stdin.on('end', () => {
37
36
  headers: {
38
37
  'Content-Type': 'application/json',
39
38
  'Content-Length': body.length,
40
- '${Kn}': ${JSON.stringify(e)}
39
+ '${on}': ${JSON.stringify(e)}
41
40
  }
42
41
  }, (res) => { res.resume(); });
43
42
  req.on('error', () => {});
44
43
  req.end(body);
45
44
  });
46
45
  process.stdin.resume();
47
- `}function jS(t,e){return`#!/usr/bin/env node
46
+ `}function Cg(t,e){return`#!/usr/bin/env node
48
47
  const http = require('http');
49
- const fallback = ${JSON.stringify(JSON.stringify(Jn))};
48
+ const fallback = ${JSON.stringify(JSON.stringify(an))};
50
49
  const chunks = [];
51
50
  process.stdin.on('data', (chunk) => chunks.push(chunk));
52
51
  process.stdin.on('end', () => {
@@ -59,7 +58,7 @@ process.stdin.on('end', () => {
59
58
  headers: {
60
59
  'Content-Type': 'application/json',
61
60
  'Content-Length': body.length,
62
- '${Kn}': ${JSON.stringify(e)}
61
+ '${on}': ${JSON.stringify(e)}
63
62
  }
64
63
  }, (res) => {
65
64
  const responseChunks = [];
@@ -80,39 +79,39 @@ process.stdin.on('end', () => {
80
79
  req.end(body);
81
80
  });
82
81
  process.stdin.resume();
83
- `}function qd(t,e){let n=(0,Yn.join)((0,Fd.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,Ud.randomUUID)()}`);(0,gt.mkdirSync)(n,{recursive:!0});let r=(0,Yn.join)(n,"settings.json"),s=(0,Yn.join)(n,"session_hook_forwarder.cjs"),i=(0,Yn.join)(n,"permission_hook_forwarder.cjs");return(0,gt.writeFileSync)(s,GS(t,e),"utf8"),(0,gt.writeFileSync)(i,jS(t,e),"utf8"),(0,gt.writeFileSync)(r,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(s)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:r,sessionScriptPath:s,permissionScriptPath:i}}function cs(t){if(t)try{(0,gt.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var ke=K.child({module:"claude"}),Vd="claude-permission-denial:",VS=/\u001B\[[0-?]*[ -/]*[@-~]/g;function zS(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function Io(t){zS()&&os(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
84
- `)}function YS(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
85
- `):""}function KS(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function JS(t){if(typeof t=="string")return t;let e=YS(t);return e||(KS(t)?"":JSON.stringify(t))}function QS(t){return/requested permissions|haven't granted/i.test(t)}function $d(t){return t.replace(VS,"").replace(/\s+/g," ").trim()}function XS(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function ZS(t){return/\brate limit\b/i.test(t)||/\busage limit\b/i.test(t)||/\bquota\b/i.test(t)||/\btoo many requests\b/i.test(t)||/\bcredit balance\b/i.test(t)||/\bcredits? remaining\b/i.test(t)||/\bmax(?:imum)? usage\b/i.test(t)}function ev(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Wd(t){let e=$d(t.resultText??""),n=(t.stderrLines??[]).map($d).filter(Boolean).slice(-3),r=[e,...n].find(i=>!!i&&ZS(i));if(r)return ev(r);let s=[e,...n].find(i=>!!i&&!XS(i));return s?t.exitCode!=null&&s!==e?`Claude exited with code ${t.exitCode}: ${s}`:s:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function us(t){return t.startsWith(Vd)}var Qn=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;emittedToolCallIds=new Set;replayPhase=!1;hookPort=null;hookSecret=null;hookFiles=null;buildClaudeEnv(){let e=C.buildSanitizedEnv();for(let n of Object.keys(e))n.startsWith("CMUX_")&&delete e[n];return e}async start(e,n,r){return this.cwd=e,this.approvalMode=r,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),ke.info({sessionId:this.sessionId,cwd:e},"session initialized"),k.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e,n){let r=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];n&&r.push("--model",n),this.sessionId&&!this.sessionId.startsWith("pending_")&&r.push("--resume",this.sessionId),cs(this.hookFiles),this.hookFiles=null,this.approvalMode!=="plan"&&this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=qd(this.hookPort,this.hookSecret),r.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="plan"&&r.push("--permission-mode","plan"),this.approvalMode==="acceptEdits"&&r.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&r.push("--dangerously-skip-permissions");let s=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;ke.info({sessionId:this.sessionId,label:s,promptPreview:e.slice(0,50)},"running claude"),Io(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.replayPhase=!0;let i=C.claudePath,o,a=r;if(C.isTransientPath(i)||i==="claude"){let c=C.execViaLoginShell("claude",r);o=c.command,a=c.args}else o=i;this.proc=(0,Gd.spawn)(o,a,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",c=>{let u=c.message;c.code==="ENOENT"&&this.cwd&&!(0,jd.existsSync)(this.cwd)&&(u=`Working directory does not exist: ${this.cwd}`),ke.error({sessionId:this.sessionId,error:u,cwd:this.cwd},"spawn error"),k.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:u}),this.handler?.({type:"error",sessionId:this.sessionId,message:u})}),this.buffer="",this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let u=this.buffer.split(`
86
- `);this.buffer=u.pop();for(let d of u)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{ke.warn({sessionId:this.sessionId,linePreview:d.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let u=c.toString().trim();u&&(ke.debug({sessionId:this.sessionId,stderr:u},"stderr"),this.lastStderr.push(u),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(c,u)=>{ke.info({sessionId:this.sessionId,exitCode:c,signal:u},"process exited");let d=this.interrupted;this.proc=null,cs(this.hookFiles),this.hookFiles=null,this.interrupted=!1,d&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):c&&c!==0&&!this.sawFinalResult&&(ke.error({sessionId:this.sessionId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Wd({stderrLines:this.lastStderr,exitCode:c})})),this.exitHandler?.(c)})}respondApproval(e,n){if(ke.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return ke.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let r=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(r+`
87
- `),!0}setApprovalMode(e){this.approvalMode=e,ke.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),ke.info({sessionId:this.sessionId},"interrupted"))}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,cs(this.hookFiles),this.hookFiles=null}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let r=e.session_id??"";r&&r!==this.sessionId&&(ke.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),k.emit("driver.init",{agent:"claude",sessionId:r}),this.sessionId=r);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)s.type==="tool_use"&&!this.emittedToolCallIds.has(s.id)&&(this.emittedToolCallIds.add(s.id),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:s.name,input:s.input??{},toolCallId:s.id}));break}case"user":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)if(s.type==="tool_result"){let i=JS(s.content);if(!i)continue;if(s.is_error===!0&&typeof s.tool_use_id=="string"&&QS(i)){this.pendingPermissionDescriptions.set(s.tool_use_id,i);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:s.tool_use_id,output:i})}break}case"control_request":{this.replayPhase=!1;let r=e.request;r?.subtype==="can_use_tool"&&(k.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:r.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:r.tool_name??"unknown",input:r.input??{},description:r.description??r.title??""}));break}case"stream_event":{this.replayPhase=!1;let r=e.event;r?.type==="content_block_delta"&&r?.delta?.type==="text_delta"&&r?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:r.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let r=typeof e.result=="string"?e.result:"";if(e.is_error){Io("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Wd({resultText:r,stderrLines:this.lastStderr})});break}let s=Array.isArray(e.permission_denials)?e.permission_denials:[];if(s.length>0){let a=s[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,c=typeof a.tool_name=="string"?a.tool_name:"unknown",u=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${c}.`;k.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:c}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${Vd}${l}`,toolName:c,input:u,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens}:void 0;Io("Claude finished. Run `claude --continue` to continue on desktop."),k.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:i,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:i,usage:o});break}}}};var Jd=require("child_process"),Qd=require("fs");var xo=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let r=this.counters.get(e),s=JSON.stringify(n),i=r.find(o=>JSON.stringify(o.labels)===s);i?i.value++:r.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let r=Math.round(performance.now()-n),s=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return s.count++,s.totalMs+=r,s.minMs=Math.min(s.minMs,r),s.maxMs=Math.max(s.maxMs,r),s.lastMs=r,this.timers.set(e,s),r}}snapshot(){let e={};for(let[s,i]of this.counters)e[s]=i.map(o=>({...o}));let n={};for(let[s,i]of this.timers)n[s]={...i,minMs:i.minMs===1/0?0:i.minMs};let r={};for(let[s,i]of this.gauges)r[s]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:r}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();K.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},R=new xo;var zd=require("node:fs"),Co=require("node:path"),tv="@vibelet/cli";function nv(t){try{let e=JSON.parse((0,zd.readFileSync)(t,"utf8"));if(e.name===tv&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function rv(){return"1.0.6"}var an=rv();var $=K.child({module:"codex"});function sv(t){switch(t.kind){case"request-user-input-approval":return{provider:"codex",kind:t.kind,rpcId:t.rpcId,questionId:t.questionId,approveLabel:t.approveLabel,denyLabel:t.denyLabel};default:return{provider:"codex",kind:t.kind,rpcId:t.rpcId}}}function iv(t){let e=t.approvalContext;if(!e||e.provider!=="codex")return null;switch(e.kind){case"command-execution":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"file-change":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"request-user-input-approval":return!e.questionId||!e.approveLabel||!e.denyLabel?null:{kind:e.kind,rpcId:e.rpcId,questionId:e.questionId,approveLabel:e.approveLabel,denyLabel:e.denyLabel,toolName:t.toolName,input:t.input};case"exec-command-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"apply-patch-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};default:return null}}function _e(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function z(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}var ov=new Set(["aborted","interrupted","cancelled","canceled"]);function av(t){let e=z(t);return e?e.toLowerCase():null}function lv(t){let e=z(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function To(t){return t?z(t.itemId)??z(t.id)??z(t.callId)??z(t.call_id):null}function Ro(t,e){let n={};for(let[r,s]of Object.entries(t))e.includes(r)||(n[r]=s);return n}function Xd(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function Zd(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function cv(t){if(!Array.isArray(t))return null;for(let e of t){let n=_e(e);if(!n)continue;let r=z(n.id),s=Array.isArray(n.options)?n.options.map(l=>_e(l)).filter(l=>!!l):[];if(!r||s.length===0)continue;let i=s.map(l=>z(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>Xd(l))??i[0],a=i.find(l=>Zd(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:r,approveLabel:o,denyLabel:a}}return null}function uv(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(s=>_e(s)).filter(s=>!!s).flatMap(s=>(Array.isArray(s.options)?s.options:[]).map(o=>_e(o)).filter(o=>!!o).map(o=>z(o.label)).filter(o=>!!o)),n=e.some(s=>Xd(s)),r=e.some(s=>Zd(s));return n&&r}function Yd(t){let e=lv(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:Ro(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:Ro(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=z(t.server),r=z(t.tool)??z(t.name);return r?{toolName:n?`mcp__${n}__${r}`:r,input:_e(t.arguments)??_e(t.input)??{}}:null}return null}function dv(t){if(!Array.isArray(t))return"";for(let e of t){let n=_e(e);if(!n)continue;let r=z(n.question)??z(n.header);if(r)return r}return""}function Kd(t,e){return t==="autoApprove"?{approvalPolicy:"never",sandbox:"danger-full-access",sandboxPolicy:{type:"dangerFullAccess"}}:t==="plan"?{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}:{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[e],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}}var Xn=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;turnStartInFlight=!1;interruptRequestedDuringTurnStart=!1;approvalMode;cwd="";model;async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=C.codexPath,i,o=this.buildSpawnArgs();if(C.isTransientPath(s)||s==="codex"){let u=C.execViaLoginShell("codex",o);i=u.command,o=u.args,$.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=s,$.info({spawnCmd:i,args:o},"spawning");k.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,Jd.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:C.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",u=>{let d=u.message;u.code==="ENOENT"&&e&&!(0,Qd.existsSync)(e)&&(d=`Working directory does not exist: ${e}`),$.error({error:d,cwd:e},"spawn error"),k.emit("driver.error",{agent:"codex",error:d})}),this.proc.stdout.on("data",u=>{this.buffer+=u.toString();let d=this.buffer.split(`
88
- `);this.buffer=d.pop();for(let f of d)if(f.trim())try{this.handleRaw(JSON.parse(f))}catch{$.warn({linePreview:f.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",u=>{let d=u.toString().trim();d&&($.debug({stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",u=>{$.info({threadId:this.threadId,exitCode:u},"process exited"),u&&u!==0&&$.error({threadId:this.threadId,exitCode:u,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:d}]of this.pending)d(new Error(`Codex process exited with code ${u}`));this.pending.clear(),this.exitHandler?.(u),u&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${u}`})});let l=R.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:an},capabilities:{experimentalApi:!0}}),l(),this.rpcNotify("initialized",{});let c=Kd(this.approvalMode,e);if(n){let u=await this.rpc("thread/resume",{threadId:n,approvalPolicy:c.approvalPolicy,sandbox:c.sandbox,persistExtendedHistory:!0});this.threadId=u?.thread?.id??n,$.info({threadId:this.threadId},"thread resumed"),k.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let u=await this.rpc("thread/start",{cwd:e,approvalPolicy:c.approvalPolicy,sandbox:c.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=u?.thread?.id??u?.threadId??"",$.info({threadId:this.threadId},"thread created"),k.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}setModel(e){this.model=e}buildSpawnArgs(){let e=["app-server","--listen","stdio://"];return this.model&&e.push("-m",this.model),e}sendPrompt(e,n){let r=Kd(this.approvalMode,this.cwd||process.cwd());this.turnStartInFlight=!0,this.interruptRequestedDuringTurnStart=!1,$.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:r.approvalPolicy,sandboxPolicy:r.sandboxPolicy}).then(s=>{$.debug({resultPreview:JSON.stringify(s).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(s=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,$.error({threadId:this.threadId,error:s.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:s.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let r=this.approvalRequests.get(e),s=r?.rpcId??Number(e);if(!Number.isFinite(s))return!1;let i;if(!r)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(r.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[r.questionId]:{answers:[n?r.approveLabel:r.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:n?"approved":"denied"};break;default:i={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return $.info({threadId:this.threadId,rpcId:s,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,result:i})+`
89
- `),!0}restorePendingApproval(e){let n=iv(e);n&&this.approvalRequests.set(e.requestId,n)}interrupt(){this.turnStartInFlight&&(this.interruptRequestedDuringTurnStart=!0),this.requestTurnInterrupt()}setApprovalMode(e){this.approvalMode=e,$.info({approvalMode:e},"approval mode updated (takes effect on subsequent turns)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let r=++this.rpcId,s=R.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(r,{resolve:a=>{s(),i(a)},reject:a=>{s(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(r),s(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:r,params:n})+`
90
- `),setTimeout(()=>{this.pending.has(r)&&(this.pending.delete(r),$.error({method:e,rpcId:r,threadId:this.threadId},"RPC timeout"),s(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}requestTurnInterrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
82
+ `}function bc(t,e){let n=(0,sn.join)((0,Sc.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,_c.randomUUID)()}`);(0,Ne.mkdirSync)(n,{recursive:!0});let r=(0,sn.join)(n,"settings.json"),s=(0,sn.join)(n,"session_hook_forwarder.cjs"),i=(0,sn.join)(n,"permission_hook_forwarder.cjs");return(0,Ne.writeFileSync)(s,xg(t,e),"utf8"),(0,Ne.writeFileSync)(i,Cg(t,e),"utf8"),(0,Ne.writeFileSync)(r,JSON.stringify({hooks:{SessionStart:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(s)}`}]}],PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`${JSON.stringify(process.execPath)} ${JSON.stringify(i)}`}]}]}},null,2),"utf8"),{secret:e,dirPath:n,settingsPath:r,sessionScriptPath:s,permissionScriptPath:i}}function ar(t){if(t)try{(0,Ne.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var ne=P.child({module:"claude"}),xc="claude-permission-denial:",kg=/\u001B\[[0-?]*[ -/]*[@-~]/g;function Eg(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function ti(t){Eg()&&sr(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
83
+ `)}function Pg(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
84
+ `):""}function Rg(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function Mg(t){if(typeof t=="string")return t;let e=Pg(t);return e||(Rg(t)?"":JSON.stringify(t))}function Lg(t){return/requested permissions|haven't granted/i.test(t)}function wc(t){return t.replace(kg,"").replace(/\s+/g," ").trim()}function Ng(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function Og(t){return/\brate limit\b/i.test(t)||/\busage limit\b/i.test(t)||/\bquota\b/i.test(t)||/\btoo many requests\b/i.test(t)||/\bcredit balance\b/i.test(t)||/\bcredits? remaining\b/i.test(t)||/\bmax(?:imum)? usage\b/i.test(t)}function Bg(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Ic(t){let e=wc(t.resultText??""),n=(t.stderrLines??[]).map(wc).filter(Boolean).slice(-3),r=[e,...n].find(i=>!!i&&Og(i));if(r)return Bg(r);let s=[e,...n].find(i=>!!i&&!Ng(i));return s?t.exitCode!=null&&s!==e?`Claude exited with code ${t.exitCode}: ${s}`:s:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function lr(t){return t.startsWith(xc)}var ln=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;emittedToolCallIds=new Set;replayPhase=!1;hookPort=null;hookSecret=null;hookFiles=null;buildClaudeEnv(){let e=S.buildSanitizedEnv();for(let n of Object.keys(e))n.startsWith("CMUX_")&&delete e[n];return e}async start(e,n,r){return this.cwd=e,this.approvalMode=r,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),ne.info({sessionId:this.sessionId,cwd:e},"session initialized"),I.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e,n){let r=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];n&&r.push("--model",n),this.sessionId&&!this.sessionId.startsWith("pending_")&&r.push("--resume",this.sessionId),ar(this.hookFiles),this.hookFiles=null,this.approvalMode!=="plan"&&this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=bc(this.hookPort,this.hookSecret),r.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="plan"&&r.push("--permission-mode","plan"),this.approvalMode==="acceptEdits"&&r.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&r.push("--dangerously-skip-permissions");let s=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;ne.info({sessionId:this.sessionId,label:s,promptPreview:e.slice(0,50)},"running claude"),ti(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.replayPhase=!0;let i=S.claudePath,o,a=r;if(S.isTransientPath(i)||i==="claude"){let c=S.execViaLoginShell("claude",r);o=c.command,a=c.args}else o=i;this.proc=(0,Ac.spawn)(o,a,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",c=>{let u=c.message;c.code==="ENOENT"&&this.cwd&&!(0,Tc.existsSync)(this.cwd)&&(u=`Working directory does not exist: ${this.cwd}`),ne.error({sessionId:this.sessionId,error:u,cwd:this.cwd},"spawn error"),I.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:u}),this.handler?.({type:"error",sessionId:this.sessionId,message:u})}),this.buffer="",this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let u=this.buffer.split(`
85
+ `);this.buffer=u.pop();for(let d of u)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{ne.warn({sessionId:this.sessionId,linePreview:d.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let u=c.toString().trim();u&&(ne.debug({sessionId:this.sessionId,stderr:u},"stderr"),this.lastStderr.push(u),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(c,u)=>{ne.info({sessionId:this.sessionId,exitCode:c,signal:u},"process exited");let d=this.interrupted;this.proc=null,ar(this.hookFiles),this.hookFiles=null,this.interrupted=!1,d&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):c&&c!==0&&!this.sawFinalResult&&(ne.error({sessionId:this.sessionId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Ic({stderrLines:this.lastStderr,exitCode:c})})),this.exitHandler?.(c)})}respondApproval(e,n){if(ne.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return ne.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let r=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(r+`
86
+ `),!0}setApprovalMode(e){this.approvalMode=e,ne.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),ne.info({sessionId:this.sessionId},"interrupted"))}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,ar(this.hookFiles),this.hookFiles=null}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let r=e.session_id??"";r&&r!==this.sessionId&&(ne.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),I.emit("driver.init",{agent:"claude",sessionId:r}),this.sessionId=r);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)s.type==="tool_use"&&!this.emittedToolCallIds.has(s.id)&&(this.emittedToolCallIds.add(s.id),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:s.name,input:s.input??{},toolCallId:s.id}));break}case"user":{if(this.replayPhase)break;let r=e.message?.content;if(!Array.isArray(r))break;for(let s of r)if(s.type==="tool_result"){let i=Mg(s.content);if(!i)continue;if(s.is_error===!0&&typeof s.tool_use_id=="string"&&Lg(i)){this.pendingPermissionDescriptions.set(s.tool_use_id,i);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:s.tool_use_id,output:i})}break}case"control_request":{this.replayPhase=!1;let r=e.request;r?.subtype==="can_use_tool"&&(I.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:r.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:r.tool_name??"unknown",input:r.input??{},description:r.description??r.title??""}));break}case"stream_event":{this.replayPhase=!1;let r=e.event;r?.type==="content_block_delta"&&r?.delta?.type==="text_delta"&&r?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:r.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let r=typeof e.result=="string"?e.result:"";if(e.is_error){ti("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Ic({resultText:r,stderrLines:this.lastStderr})});break}let s=Array.isArray(e.permission_denials)?e.permission_denials:[];if(s.length>0){let a=s[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,c=typeof a.tool_name=="string"?a.tool_name:"unknown",u=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${c}.`;I.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:c}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${xc}${l}`,toolName:c,input:u,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens}:void 0;ti("Claude finished. Run `claude --continue` to continue on desktop."),I.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:i,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:i,usage:o});break}}}};var Pc=require("child_process"),Rc=require("fs");var ni=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let r=this.counters.get(e),s=JSON.stringify(n),i=r.find(o=>JSON.stringify(o.labels)===s);i?i.value++:r.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let r=Math.round(performance.now()-n),s=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return s.count++,s.totalMs+=r,s.minMs=Math.min(s.minMs,r),s.maxMs=Math.max(s.maxMs,r),s.lastMs=r,this.timers.set(e,s),r}}snapshot(){let e={};for(let[s,i]of this.counters)e[s]=i.map(o=>({...o}));let n={};for(let[s,i]of this.timers)n[s]={...i,minMs:i.minMs===1/0?0:i.minMs};let r={};for(let[s,i]of this.gauges)r[s]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:r}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();P.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},w=new ni;var Cc=require("node:fs"),ri=require("node:path"),Dg="@vibelet/cli";function Hg(t){try{let e=JSON.parse((0,Cc.readFileSync)(t,"utf8"));if(e.name===Dg&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function Fg(){return"1.0.7"}var wt=Fg();var x=P.child({module:"codex"});function Ug(t){switch(t.kind){case"request-user-input-approval":return{provider:"codex",kind:t.kind,rpcId:t.rpcId,questionId:t.questionId,approveLabel:t.approveLabel,denyLabel:t.denyLabel};default:return{provider:"codex",kind:t.kind,rpcId:t.rpcId}}}function qg(t){let e=t.approvalContext;if(!e||e.provider!=="codex")return null;switch(e.kind){case"command-execution":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"file-change":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"request-user-input-approval":return!e.questionId||!e.approveLabel||!e.denyLabel?null:{kind:e.kind,rpcId:e.rpcId,questionId:e.questionId,approveLabel:e.approveLabel,denyLabel:e.denyLabel,toolName:t.toolName,input:t.input};case"exec-command-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"apply-patch-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};default:return null}}function $(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function E(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}var Wg=new Set(["aborted","interrupted","cancelled","canceled"]);function Gg(t){let e=E(t);return e?e.toLowerCase():null}function jg(t){let e=E(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function si(t){return t?E(t.itemId)??E(t.id)??E(t.callId)??E(t.call_id):null}function ii(t,e){let n={};for(let[r,s]of Object.entries(t))e.includes(r)||(n[r]=s);return n}function Mc(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function Lc(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function Vg(t){if(!Array.isArray(t))return null;for(let e of t){let n=$(e);if(!n)continue;let r=E(n.id),s=Array.isArray(n.options)?n.options.map(l=>$(l)).filter(l=>!!l):[];if(!r||s.length===0)continue;let i=s.map(l=>E(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>Mc(l))??i[0],a=i.find(l=>Lc(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:r,approveLabel:o,denyLabel:a}}return null}function $g(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(s=>$(s)).filter(s=>!!s).flatMap(s=>(Array.isArray(s.options)?s.options:[]).map(o=>$(o)).filter(o=>!!o).map(o=>E(o.label)).filter(o=>!!o)),n=e.some(s=>Mc(s)),r=e.some(s=>Lc(s));return n&&r}function kc(t){let e=jg(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:ii(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:ii(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=E(t.server),r=E(t.tool)??E(t.name);return r?{toolName:n?`mcp__${n}__${r}`:r,input:$(t.arguments)??$(t.input)??{}}:null}return null}function zg(t){if(!Array.isArray(t))return"";for(let e of t){let n=$(e);if(!n)continue;let r=E(n.question)??E(n.header);if(r)return r}return""}function Ec(t,e){return t==="autoApprove"?{approvalPolicy:"never",sandbox:"danger-full-access",sandboxPolicy:{type:"dangerFullAccess"}}:t==="plan"?{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}:{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[e],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}}var cn=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;turnStartInFlight=!1;interruptRequestedDuringTurnStart=!1;approvalMode;cwd="";model;async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(s)||s==="codex"){let u=S.execViaLoginShell("codex",o);i=u.command,o=u.args,x.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=s,x.info({spawnCmd:i,args:o},"spawning");I.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,Pc.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0}:{}}),this.proc.on("error",u=>{let d=u.message;u.code==="ENOENT"&&e&&!(0,Rc.existsSync)(e)&&(d=`Working directory does not exist: ${e}`),x.error({error:d,cwd:e},"spawn error"),I.emit("driver.error",{agent:"codex",error:d})}),this.proc.stdout.on("data",u=>{this.buffer+=u.toString();let d=this.buffer.split(`
87
+ `);this.buffer=d.pop();for(let f of d)if(f.trim())try{this.handleRaw(JSON.parse(f))}catch{x.warn({linePreview:f.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",u=>{let d=u.toString().trim();d&&(x.debug({stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",u=>{x.info({threadId:this.threadId,exitCode:u},"process exited"),u&&u!==0&&x.error({threadId:this.threadId,exitCode:u,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:d}]of this.pending)d(new Error(`Codex process exited with code ${u}`));this.pending.clear(),this.exitHandler?.(u),u&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${u}`})});let l=w.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:wt},capabilities:{experimentalApi:!0}}),l(),this.rpcNotify("initialized",{});let c=Ec(this.approvalMode,e);if(n){let u=await this.rpc("thread/resume",{threadId:n,approvalPolicy:c.approvalPolicy,sandbox:c.sandbox,persistExtendedHistory:!0});this.threadId=u?.thread?.id??n,x.info({threadId:this.threadId},"thread resumed"),I.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let u=await this.rpc("thread/start",{cwd:e,approvalPolicy:c.approvalPolicy,sandbox:c.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=u?.thread?.id??u?.threadId??"",x.info({threadId:this.threadId},"thread created"),I.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}setModel(e){this.model=e}buildSpawnArgs(){let e=["app-server","--listen","stdio://"];return this.model&&e.push("-m",this.model),e}sendPrompt(e,n){let r=Ec(this.approvalMode,this.cwd||process.cwd());this.turnStartInFlight=!0,this.interruptRequestedDuringTurnStart=!1,x.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:r.approvalPolicy,sandboxPolicy:r.sandboxPolicy}).then(s=>{x.debug({resultPreview:JSON.stringify(s).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(s=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,x.error({threadId:this.threadId,error:s.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:s.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let r=this.approvalRequests.get(e),s=r?.rpcId??Number(e);if(!Number.isFinite(s))return!1;let i;if(!r)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(r.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[r.questionId]:{answers:[n?r.approveLabel:r.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:n?"approved":"denied"};break;default:i={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return x.info({threadId:this.threadId,rpcId:s,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,result:i})+`
88
+ `),!0}restorePendingApproval(e){let n=qg(e);n&&this.approvalRequests.set(e.requestId,n)}interrupt(){this.turnStartInFlight&&(this.interruptRequestedDuringTurnStart=!0),this.requestTurnInterrupt()}setApprovalMode(e){this.approvalMode=e,x.info({approvalMode:e},"approval mode updated (takes effect on subsequent turns)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let r=++this.rpcId,s=w.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(r,{resolve:a=>{s(),i(a)},reject:a=>{s(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(r),s(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:r,params:n})+`
89
+ `),setTimeout(()=>{this.pending.has(r)&&(this.pending.delete(r),x.error({method:e,rpcId:r,threadId:this.threadId},"RPC timeout"),s(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}requestTurnInterrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
91
90
  `)}writeServerRequestError(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:e,error:{code:-32601,message:n}})+`
92
- `)}resolveToolContext(e){let n=_e(e?.item)??e??null,r=To(n);if(!r)return null;let s=n?Yd(n):null;if(s)return this.toolContextByCallId.set(r,s),{callId:r,toolContext:s};let i=this.toolContextByCallId.get(r);return i?{callId:r,toolContext:i}:null}createFallbackInput(e,n){return e?Ro(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,r){if(this.approvalRequests.set(e,n),k.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){$.warn({threadId:this.threadId,requestId:e,toolName:n.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(n.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:n.toolName,input:n.input,description:r,approvalContext:sv(n)})}handleServerRequest(e,n,r){let s=String(n),i=this.resolveToolContext(r);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(s,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},z(r?.reason)??z(r?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(s,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},z(r?.reason)??z(r?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=r?.questions;if(!uv(o)){$.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=cv(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(s,{kind:"request-user-input-approval",rpcId:n,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","questions"])},dv(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(s,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,[])},z(r?.reason)??z(r?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(s,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,[])},z(r?.reason)??z(r?.description)??"");return}if(e==="item/permissions/requestApproval"){$.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}$.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if($.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let s=this.pending.get(e.id);this.pending.delete(e.id),e.error?s.reject(new Error(e.error.message??"RPC error")):s.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,r=_e(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,r??void 0);return}switch(n&&$.debug({method:n,paramsPreview:JSON.stringify(r??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let s=r?.text??r?.delta??r?.content??"";s&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:s}):s||$.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:String(r.output)});break;case"item/started":{let s=_e(r?.item),i=To(s),o=s?Yd(s):null;i&&o&&(this.toolContextByCallId.set(i,o),this.handler&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:o.toolName,input:o.input,toolCallId:i}));break}case"item/completed":{let s=_e(r?.item)??r,i=To(s);i&&this.toolContextByCallId.delete(i);break}case"turn/aborted":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=z(r?.reason)??z(_e(r?.turn)?.reason);$.info({threadId:this.threadId,reason:s},"turn interrupted"),k.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,...s?{reason:s}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}case"turn/completed":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=_e(r?.turn),i=av(s?.status),o=_e(r?.usage),a=o?{inputTokens:Number(o.input_tokens??o.inputTokens??0),outputTokens:Number(o.output_tokens??o.outputTokens??0)}:void 0;if(i&&ov.has(i)){$.info({threadId:this.threadId,status:i},"turn interrupted"),k.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...a?{usage:a}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}$.info({threadId:this.threadId,status:i??"completed"},"turn completed"),k.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:a}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:a});break}default:n&&$.debug({method:n},"unhandled notification");break}}};var J=require("fs/promises"),$a=require("fs"),Wa=require("readline"),Q=require("path"),tt=require("os");var fv=new Set(["New session","Resumed session","Untitled session"]),hv=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function pv(t){return t.replace(/\s+/g," ").trim()}function ds(t){return typeof t!="string"?void 0:pv(t)||void 0}function ef(t){let e=ds(t);return e?/^[0-9a-f]{8,}$/i.test(e)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||/^agent-[a-z0-9_-]{6,}$/i.test(e):!1}function ln(t){let e=ds(t);return!e||fv.has(e)||ef(e)}function gv(t){for(let e of t.replace(/\r/g,"").split(`
93
- `)){let n=ds(e);if(n&&!mv(n)&&!yv(n))return n}}function mv(t){return hv.some(e=>t.startsWith(e))}function yv(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function _v(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="\u3002"||n==="\uFF01"||n==="\uFF1F"||n==="\uFF1B")return e+1;if(n==="."||n==="!"||n==="?"||n===";"){let r=t[e+1];if(!r||/\s/.test(r))return e+1}}return-1}function ko(t,e=80){if(typeof t!="string")return;let n=gv(t);if(!n)return;let r=_v(n),i=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||ef(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function Nt(t,e){for(let n of t){let r=ds(n);if(!(!r||ln(r)))return r}return ko(e)}var rf=require("child_process"),sf=require("util");var of=(0,sf.promisify)(rf.execFile),af=5e3,Sv=2500,vv=3e3,lf=8,fs=new Map,Po=new Map,tf=null;function wv(t){let e=fs.get(t);return e?Date.now()>e.expiresAt?(fs.delete(t),null):e.value??void 0:null}function bv(t,e){if(e===void 0){fs.delete(t);return}fs.set(t,{value:e,expiresAt:Date.now()+af})}async function Av(t){if(!t)return;if(tf)return tf(t);let e=[["branch","--show-current"],["rev-parse","--abbrev-ref","HEAD"]];for(let n of e)try{let{stdout:r}=await of("git",["-C",t,...n],{env:Lt(),timeout:Sv,maxBuffer:65536}),s=r.trim();if(s&&s!=="HEAD")return s}catch{}}async function Ev(t){let e=wv(t);if(e!==null)return e;let n=Po.get(t);if(n)return n;let r=Av(t).then(s=>(bv(t,s),s)).finally(()=>{Po.delete(t)});return Po.set(t,r),r}async function cf(t,e,n){if(t.length===0)return;let r=Math.max(1,Math.min(e,t.length)),s=0;await Promise.all(Array.from({length:r},async()=>{for(;;){let i=s;if(s+=1,i>=t.length)return;await n(t[i])}}))}async function uf(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await cf(e,lf,async r=>{n.set(r,await Ev(r))}),n}var Lo=new Map,Mo=new Map,nf=null;function Iv(t,e){if(e===void 0){Lo.delete(t);return}Lo.set(t,{value:e,expiresAt:Date.now()+af})}async function xv(t){if(t){if(nf)return nf(t);for(let e=0;e<2;e+=1)try{let{stdout:n}=await of("git",["-C",t,"diff","HEAD","--shortstat"],{env:Lt(),timeout:vv,maxBuffer:65536}),r=n.trim();if(!r)return;let s=r.match(/(\d+) insertion/),i=r.match(/(\d+) deletion/),o=s?Number(s[1]):0,a=i?Number(i[1]):0;return o===0&&a===0?void 0:{additions:o,deletions:a}}catch{if(e===1)return}}}async function Cv(t){let e=Lo.get(t);if(e&&Date.now()<=e.expiresAt)return e.value;let n=Mo.get(t);if(n)return n;let r=xv(t).then(s=>(Iv(t,s),s)).finally(()=>{Mo.delete(t)});return Mo.set(t,r),r}async function df(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await cf(e,lf,async r=>{n.set(r,await Cv(r))}),n}var dp=St(lp(),1),Bt=require("fs/promises"),Ma=require("os"),Ns=require("path");var Ls=K.child({module:"activity-watcher"}),Hb=12e4,Bb=5e3,Fb=6e4,Ub=5;function qb(){return(0,Ns.join)((0,Ma.homedir)(),".claude","projects")}function $b(){return(0,Ns.join)((0,Ma.homedir)(),".codex","sessions")}async function cp(t){try{return await(0,Bt.realpath)(t)}catch{return t}}function up(t,e){return!(!t.endsWith(".jsonl")||e==="claude"&&t.includes("/subagents/"))}var Pa=class{entries=new Map;filePathIndex=new Map;metaInFlight=new Map;roots=new Map;watcher=null;rescanTimer=null;listeners=new Set;started=!1;async start(e){if(this.started)return;this.started=!0;let n=await cp(e?.claudeDir??qb()),r=await cp(e?.codexDir??$b());this.roots.set(n,"claude"),this.roots.set(r,"codex"),await Promise.all([this.bootstrap("claude",n),this.bootstrap("codex",r)]),this.updateGauges();let s=dp.default.watch([n,r],{ignoreInitial:!0,persistent:!0,ignorePermissionErrors:!0,awaitWriteFinish:!1,atomic:!1,usePolling:e?.usePolling??!1,interval:e?.pollingIntervalMs??100,binaryInterval:e?.pollingIntervalMs??300});this.watcher=s,s.on("add",(i,o)=>void this.handleFsChange(i,o?.mtimeMs)),s.on("change",(i,o)=>void this.handleFsChange(i,o?.mtimeMs)),s.on("unlink",i=>this.handleUnlink(i)),s.on("error",i=>{Ls.warn({error:String(i)},"activity watcher error")}),await new Promise(i=>{s.once("ready",()=>i())}),this.rescanTimer=setInterval(()=>{this.safetyRescan().catch(i=>{Ls.warn({error:String(i)},"activity watcher rescan failed")})},Fb),this.rescanTimer.unref?.(),Ls.info({seeded:this.entries.size},"activity watcher started")}async stop(){if(this.started){if(this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null),this.watcher){let e=this.watcher;this.watcher=null,await e.close().catch(()=>{})}this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}}identifyAgent(e){for(let[n,r]of this.roots)if(e===n||e.startsWith(`${n}/`))return r;return null}listActive(e=Hb){let n=Date.now(),r=n-e,s=n-Bb,i=[];for(let o of this.entries.values())o.lastActivityMs<r||i.push({...o,isResponding:o.lastActivityMs>=s});return i}onActivity(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async bootstrap(e,n){let r=await this.walkSessionFiles(n,Ub);await Promise.all(r.map(async({filePath:s,mtimeMs:i})=>{up(s,e)&&await this.ingestPath(e,s,i,i)}))}async walkSessionFiles(e,n){let r=[],s=async(i,o)=>{if(o>n)return;let a=await(0,Bt.readdir)(i,{withFileTypes:!0}).catch(()=>[]);await Promise.all(a.map(async l=>{let c=(0,Ns.join)(i,l.name);if(l.isDirectory()){await s(c,o+1);return}if(!l.isFile()||!l.name.endsWith(".jsonl"))return;let u=await(0,Bt.stat)(c).catch(()=>null);u&&r.push({filePath:c,mtimeMs:u.mtimeMs})}))};return await s(e,0),r}async handleFsChange(e,n){let r=this.identifyAgent(e);if(!r||!up(e,r))return;let s=Date.now(),i=n??s;await this.ingestPath(r,e,s,i)&&(this.updateGauges(),this.notify())}handleUnlink(e){let n=this.filePathIndex.get(e);n&&(this.filePathIndex.delete(e),this.entries.delete(n),this.updateGauges(),this.notify())}async ingestPath(e,n,r,s){let i=this.filePathIndex.get(n);if(i)return this.touchEntry(i,r,s);let o=`${e}:${n}`,a=this.metaInFlight.get(o);return a||(a=(async()=>{try{let l=await ur(n,e);if(!l)return;let c=`${e}:${l.sessionId}`,u=this.entries.get(c);if(u){u.lastActivityMs=Math.max(u.lastActivityMs,r),u.mtimeMs=Math.max(u.mtimeMs,s),u.filePath!==n&&(this.filePathIndex.delete(u.filePath),u.filePath=n),this.filePathIndex.set(n,c);return}this.entries.set(c,{agent:e,sessionId:l.sessionId,cwd:l.cwd,title:l.title,filePath:n,lastActivityMs:r,mtimeMs:s}),this.filePathIndex.set(n,c)}finally{this.metaInFlight.delete(o)}})(),this.metaInFlight.set(o,a)),await a,this.filePathIndex.has(n)}touchEntry(e,n,r){let s=this.entries.get(e);if(!s)return!1;let i=Math.max(s.lastActivityMs,n),o=Math.max(s.mtimeMs,r);return i===s.lastActivityMs&&o===s.mtimeMs?!1:(s.lastActivityMs=i,s.mtimeMs=o,!0)}async safetyRescan(){if(this.entries.size===0)return;let e=[];for(let[r,s]of this.entries)e.push((async()=>{let i=await(0,Bt.stat)(s.filePath).catch(()=>null);return i?i.mtimeMs>s.mtimeMs?this.touchEntry(r,i.mtimeMs,i.mtimeMs):!1:(this.filePathIndex.delete(s.filePath),this.entries.delete(r),!0)})());(await Promise.all(e)).some(Boolean)&&(this.updateGauges(),this.notify())}notify(){for(let e of this.listeners)try{e()}catch(n){Ls.warn({error:String(n)},"activity listener failed")}}updateGauges(){R.gauge("session.activity_watcher.entries",this.entries.size)}__injectEntryForTests(e){let n=`${e.agent}:${e.sessionId}`;this.entries.set(n,{...e}),this.filePathIndex.set(e.filePath,n),this.updateGauges(),this.notify()}__resetForTests(){this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null),this.watcher=null,this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}},pn=new Pa;var Ft=K.child({module:"inventory"}),mp=6e3,Wb=1e4;function Gb(t){return{agent:t.agent,cwd:t.cwd,sessionId:t.sessionId,confidence:"high",sessionFilePath:t.filePath,title:t.title,isResponding:t.isResponding}}async function jb(){return pn.listActive().map(Gb)}var yp={listScannedSessions:pr,scanRunningSessions:jb,searchSessionContent:Ap},De=Vb(),fr=null,Os=0,Hs=0,Ds=0,La=0,Na=new Set;function Vb(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function zb(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,branch:t.branch,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[...t.sources].sort(),runtime:{state:t.runtime.state,confidence:t.runtime.confidence,resumeMode:t.runtime.resumeMode,pid:t.runtime.pid,command:t.runtime.command,isResponding:t.runtime.isResponding,needsAttention:t.runtime.needsAttention},managed:t.managed,approvalMode:t.approvalMode,observedApprovalMode:t.observedApprovalMode})}function Yb(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,pid:t.pid,command:t.command,confidence:t.confidence,isResponding:t.isResponding,approvalMode:t.approvalMode})}function fp(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(zb).sort(),runningSessions:t.runningSessions.map(Yb).sort()})}function Kb(){for(let t of Na)try{t()}catch(e){Ft.warn({error:String(e)},"session inventory backfill listener failed")}}function dr(){R.gauge("session.inventory.external_cached_sessions",De.scannedSessions.length),R.gauge("session.inventory.external_running_sessions",De.runningSessions.length),R.gauge("session.inventory.backfill_inflight",fr?1:0)}function _p(t){return Na.add(t),()=>{Na.delete(t)}}function Sp(){return{cachedSessions:De.scannedSessions.length,runningSessions:De.runningSessions.length,cacheAgeMs:De.refreshedAt?Math.max(0,Date.now()-De.refreshedAt):void 0,backfillInFlight:!!fr,lastBackfillDurationMs:Ds||void 0,lastBackfillCompletedAt:Hs?new Date(Hs).toISOString():void 0,lastBackfillAppliedAt:La?new Date(La).toISOString():void 0}}dr();function vp(){return pn.onActivity(()=>{bp(yp,mp)})}var gn={daemonActive:3,externalRunning:2,idle:1},hp={high:3,medium:2,low:1};function wp(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function Jb(t,e){let n=t.runtime.needsAttention?1:0,r=e.runtime.needsAttention?1:0,s=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return r-n||i-s||gn[e.runtime.state]-gn[t.runtime.state]||wp(t,e)}function Qb(t,e){return gn[e.state]>gn[t.state]?e:gn[e.state]<gn[t.state]?t:hp[e.confidence]>hp[t.confidence]?e:t}function Xb(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function Zb(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function eA(t,e){return e?t?!(ln(e)&&!ln(t)):!0:!1}function Oa(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function tA(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...Oa()},managed:t.managed,approvalMode:t.approvalMode}}function nA(t,e){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:e,lastActivityAt:e,sources:["process"],runtime:{state:"externalRunning",confidence:t.confidence,resumeMode:"resumeSession",...t.pid!==void 0?{pid:t.pid}:{},...t.command!==void 0?{command:t.command}:{},isResponding:t.isResponding},observedApprovalMode:t.approvalMode}}function rA(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||void 0,isResponding:t.isResponding||void 0},managed:t.managed,approvalMode:t.approvalMode}}function sA(t,e){for(let n of e){let r=`${n.agent}:${n.sessionId}`,s=t.get(r);if(!s){t.set(r,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=eA(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=n.branch??s.branch,l=Qb(s.runtime,n.runtime),c=s.sources.slice();for(let p of n.sources)c.includes(p)||c.push(p);let u=n.sources.includes("process"),d=s.sources.includes("process")&&!s.sources.includes("daemon"),f=u?s.lastActivityAt:d?n.lastActivityAt:Zb(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,branch:a,title:i,createdAt:Xb(s.createdAt,n.createdAt),lastActivityAt:f,sources:c,runtime:l,managed:s.managed||n.managed,approvalMode:n.approvalMode??s.approvalMode,observedApprovalMode:n.observedApprovalMode??s.observedApprovalMode})}}function iA(...t){let e=new Map;for(let n of t)sA(e,n);return[...e.values()]}function oA(t,e,n,r,s,i){let o=r?.toLowerCase(),a=t.filter(l=>{if(e&&l.agent!==e||n&&l.cwd!==n)return!1;if(o){let c=(l.title??"").toLowerCase(),u=(l.cwd??"").toLowerCase(),d=i?.[l.sessionId]?.toLowerCase()??"",f=c.includes(o)||u.includes(o)||(d?d.includes(o):!1),p=s?.has(l.sessionId)??!1;if(!f&&!p)return!1}return!0});return r&&Ft.info({total:t.length,filtered:a.length,search:r,contentMatchIds:s?.size??0},"filter applied"),a}function aA(t,e){if(!e)return 0;let n=0,r=t.length;for(;n<r;){let s=n+r>>1,i=t[s];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?r=s:n=s+1}if(n>0){let s=t[n-1];if(s.lastActivityAt===e.lastActivityAt&&s.sessionId===e.sessionId)return n}return 0}function pp(t,e,n,r,s,i,o,a){let l=i?1/0:Math.max(1,e||50),c=iA(t.sessionRecords.map(tA),t.scannedSessions,t.runningSessions.map(E=>nA(E,t.scannedAt)),t.activeSessions.map(rA)),u=t.deletedSessionIds?.size?c.filter(E=>!t.deletedSessionIds?.has(E.sessionId)):c,d=oA(u,r,s,i,o,a),f=d.filter(E=>E.runtime.state!=="idle"||E.managed).sort(Jb),p=d.filter(E=>E.runtime.state==="idle"&&!E.managed).sort(wp),g=aA(p,n),h=p.slice(g,g+l),w=g+h.length<p.length&&h.length>0?{lastActivityAt:h[h.length-1].lastActivityAt,sessionId:h[h.length-1].sessionId}:void 0;return{sessions:n?h:[...f,...h],nextCursor:w}}async function gp(t){if(t.sessions.length===0)return t;let e=t.sessions.map(o=>o.cwd),[n,r]=await Promise.all([uf(e),df(e)]),s=!1,i=t.sessions.map(o=>{let a=n.get(o.cwd),l=r.get(o.cwd);return o.branch===a&&o.diffStat===l?o:(s=!0,{...o,branch:a,diffStat:l})});return s?{...t,sessions:i}:t}function hr(t,e,n,r,s){return new Promise(i=>{let o=Date.now(),a=!1,l=null,c=u=>{a||(a=!0,l&&(clearTimeout(l),l=null),i(u))};l=setTimeout(()=>{if(a)return;let u=Array.isArray(s)&&s.length>0;Ft.warn({source:t,timeoutMs:r,durationMs:Date.now()-o,partial:u?s.length:0},u?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),c(u?s:n)},r),typeof l=="object"&&"unref"in l&&l.unref(),e().then(u=>{c(u)}).catch(u=>{a||Ft.warn({source:t,error:String(u)},"session inventory source failed, using fallback"),c(n)})})}function lA(t=Date.now()){return De.refreshedAt===0||t-De.refreshedAt>=Wb}async function cA(t,e){let n=new Date().toISOString(),r=[],[s,i]=await Promise.all([hr("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,r),[],e,r),hr("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return{scannedSessions:s,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function bp(t,e){if(fr)return;let n=Os,r=R.startTimer("session.inventory.backfill_latency_ms");fr=cA(t,e).then(s=>{if(n!==Os)return;let i=fp(De);De=s;let o=fp(s),a=r();Ds=a,Hs=Date.now(),dr(),i!==o&&(La=Date.now(),R.increment("session.inventory.backfill_applied"),Ft.info({durationMs:a,scanned:s.scannedSessions.length,running:s.runningSessions.length},"session inventory external backfill applied"),Kb())}).catch(s=>{n===Os&&(Ds=r(),Hs=Date.now(),dr(),Ft.warn({error:String(s),durationMs:Ds},"session inventory external backfill failed"))}).finally(()=>{n===Os&&(fr=null,dr())}),dr()}async function Bs(t){let e={...yp,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??mp);if(!t.search){let u=R.startTimer("session.inventory.fast_path_latency_ms");lA()&&bp(e,n);let d=De,f=pp({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:d.scannedSessions,runningSessions:d.runningSessions,scannedAt:d.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,void 0,void 0,t.customTitles);if(t.skipGitMetadata)return u(),f;let p=await gp(f);return u(),p}let r=[],s=new Date().toISOString(),i=t.search,[o,a,l]=await Promise.all([hr("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),hr("process.running_sessions",()=>e.scanRunningSessions(),[],n),hr("scanner.search_content",()=>e.searchSessionContent(i,t.agent),void 0,n)]);Ft.info({search:t.search,contentMatches:l?.size??0,scanned:o.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results");let c=pp({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:o,runningSessions:a,scannedAt:s,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,i,l,t.customTitles);return t.skipGitMetadata?c:gp(c)}var mt=K.child({module:"scanner"});function Rp(t){let e=new Map;return{get(n){let r=e.get(n);if(r){if(Date.now()>r.expiresAt){e.delete(n);return}return r.value}},set(n,r){e.set(n,{value:r,expiresAt:Date.now()+t})},clear(){e.clear()}}}var kp=3e4,Fa=Rp(kp),Ua=Rp(kp),Da=new Map,Ha=new Map,mn=24;function Us(){Fa.clear(),Ua.clear()}function Pp(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function yn(t,e,n){if(t.length===0)return[];let r=Math.max(1,Math.min(e,t.length)),s=new Array(t.length),i=0;return await Promise.all(Array.from({length:r},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;s[o]=await n(t[o],o)}})),s}function*Mp(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
94
- `,n);s===-1&&(s=t.length);let i=t.substring(n,s);n=s+1,!(i.length===0||i.trim().length===0)&&(yield i,r+=1)}}var Ba=512*1024,Ep=256*1024;async function Lp(t,e){if(e<=Ba)return(0,J.readFile)(t,"utf-8");let n=await(0,J.open)(t,"r");try{let r=Buffer.alloc(Ba),{bytesRead:s}=await n.read(r,0,Ba,0);return r.toString("utf-8",0,s)}finally{await n.close()}}async function uA(t,e){if(e<=Ep)return(0,J.readFile)(t,"utf-8");let n=await(0,J.open)(t,"r");try{let r=Math.max(0,e-Ep),s=Buffer.alloc(e-r),{bytesRead:i}=await n.read(s,0,s.length,r);return s.toString("utf-8",0,i)}finally{await n.close()}}function Ip(t){switch(t){case"plan":return"plan";case"acceptEdits":return"acceptEdits";case"bypassPermissions":return"autoApprove";case"default":return"normal";default:return}}function dA(t){let e=typeof t?.approval_policy=="string"?t.approval_policy:"",n=t?.sandbox_policy,r=typeof n?.type=="string"?n.type:"",s=Array.isArray(n?.writable_roots)?n.writable_roots:null;if(e==="never"&&r==="danger-full-access")return"autoApprove";if(e==="on-request"&&r==="workspace-write")return s?.length?"normal":"plan"}function fA(t){return t?.type==="permission-mode"?Ip(t.permissionMode):Ip(t?.permissionMode)}function hA(t){if(t?.type==="turn_context")return dA(t.payload)}async function Np(t,e,n){let r,s=await uA(t,n);for(let i of s.split(`
95
- `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=e==="claude"?fA(o):hA(o);a&&(r=a)}return r}function Ga(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").join(""):""}function Op(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?Ga(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function qs(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"||e.type!=="text"?"":typeof e.text=="string"?e.text:"").join(""):""}var pA=["<task-notification>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","<system-reminder>","<environment_context>","# AGENTS.md instructions for "];function gA(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?pA.some(r=>n.startsWith(r)):!1}function $s(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=qs(t.message.content);return gA(t,e)?"":e}function mA(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function yA(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object"||e.type!=="tool_result")return"";let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.map(r=>!r||typeof r!="object"?"":typeof r.text=="string"?r.text:typeof r.content=="string"?r.content:"").filter(Boolean).join(`
91
+ `)}resolveToolContext(e){let n=$(e?.item)??e??null,r=si(n);if(!r)return null;let s=n?kc(n):null;if(s)return this.toolContextByCallId.set(r,s),{callId:r,toolContext:s};let i=this.toolContextByCallId.get(r);return i?{callId:r,toolContext:i}:null}createFallbackInput(e,n){return e?ii(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,r){if(this.approvalRequests.set(e,n),I.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:n.toolName}),!this.handler){x.warn({threadId:this.threadId,requestId:e,toolName:n.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(n.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:n.toolName,input:n.input,description:r,approvalContext:Ug(n)})}handleServerRequest(e,n,r){let s=String(n),i=this.resolveToolContext(r);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(s,{kind:"command-execution",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},E(r?.reason)??E(r?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(s,{kind:"file-change",responseKind:"v2",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","reason","description"])},E(r?.reason)??E(r?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=r?.questions;if(!$g(o)){x.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=Vg(o);if(!a){this.writeServerRequestError(n,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(s,{kind:"request-user-input-approval",rpcId:n,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,["itemId","questions"])},zg(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(s,{kind:"exec-command-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(r,[])},E(r?.reason)??E(r?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(s,{kind:"apply-patch-legacy",rpcId:n,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(r,[])},E(r?.reason)??E(r?.description)??"");return}if(e==="item/permissions/requestApproval"){x.warn({threadId:this.threadId,rpcId:n},"unsupported permissions approval request"),this.writeServerRequestError(n,"Unsupported permissions approval request");return}x.warn({threadId:this.threadId,rpcId:n,method:e},"unsupported server request"),this.writeServerRequestError(n,`Unsupported server request: ${e}`)}handleRaw(e){if(x.debug({method:e.method??"(response)",rpcId:e.id??"-"},"handleRaw"),e.id!=null&&!e.method&&this.pending.has(e.id)){let s=this.pending.get(e.id);this.pending.delete(e.id),e.error?s.reject(new Error(e.error.message??"RPC error")):s.resolve(e.result);return}let n=typeof e.method=="string"?e.method:void 0,r=$(e.params);if(n&&e.id!=null){this.handleServerRequest(n,e.id,r??void 0);return}switch(n&&x.debug({method:n,paramsPreview:JSON.stringify(r??{}).slice(0,300)},"notification"),n){case"item/agentMessage/delta":{let s=r?.text??r?.delta??r?.content??"";s&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:s}):s||x.debug({paramsKeys:Object.keys(r??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":r?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:r.itemId??"",output:String(r.output)});break;case"item/started":{let s=$(r?.item),i=si(s),o=s?kc(s):null;i&&o&&(this.toolContextByCallId.set(i,o),this.handler&&this.handler({type:"tool.call",sessionId:this.threadId,toolName:o.toolName,input:o.input,toolCallId:i}));break}case"item/completed":{let s=$(r?.item)??r,i=si(s);i&&this.toolContextByCallId.delete(i);break}case"turn/aborted":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=E(r?.reason)??E($(r?.turn)?.reason);x.info({threadId:this.threadId,reason:s},"turn interrupted"),I.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,...s?{reason:s}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}case"turn/completed":{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;let s=$(r?.turn),i=Gg(s?.status),o=$(r?.usage),a=o?{inputTokens:Number(o.input_tokens??o.inputTokens??0),outputTokens:Number(o.output_tokens??o.outputTokens??0)}:void 0;if(i&&Wg.has(i)){x.info({threadId:this.threadId,status:i},"turn interrupted"),I.emit("session.interrupted",{agent:"codex",sessionId:this.threadId,status:i,...a?{usage:a}:{}}),this.handler&&this.handler({type:"session.interrupted",sessionId:this.threadId});break}x.info({threadId:this.threadId,status:i??"completed"},"turn completed"),I.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:a}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:a});break}default:n&&x.debug({method:n},"unhandled notification");break}}};var R=require("fs/promises"),bi=require("fs"),wi=require("readline"),M=require("path"),be=require("os");var Yg=new Set(["New session","Resumed session","Untitled session"]),Jg=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function Kg(t){return t.replace(/\s+/g," ").trim()}function cr(t){return typeof t!="string"?void 0:Kg(t)||void 0}function Nc(t){let e=cr(t);return e?/^[0-9a-f]{8,}$/i.test(e)||/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||/^agent-[a-z0-9_-]{6,}$/i.test(e):!1}function It(t){let e=cr(t);return!e||Yg.has(e)||Nc(e)}function Qg(t){for(let e of t.replace(/\r/g,"").split(`
92
+ `)){let n=cr(e);if(n&&!Xg(n)&&!Zg(n))return n}}function Xg(t){return Jg.some(e=>t.startsWith(e))}function Zg(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function em(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="\u3002"||n==="\uFF01"||n==="\uFF1F"||n==="\uFF1B")return e+1;if(n==="."||n==="!"||n==="?"||n===";"){let r=t[e+1];if(!r||/\s/.test(r))return e+1}}return-1}function oi(t,e=80){if(typeof t!="string")return;let n=Qg(t);if(!n)return;let r=em(n),i=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||Nc(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function Xe(t,e){for(let n of t){let r=cr(n);if(!(!r||It(r)))return r}return oi(e)}var Dc=require("child_process"),Hc=require("util");var Fc=(0,Hc.promisify)(Dc.execFile),Uc=5e3,tm=2500,nm=3e3,qc=8,ur=new Map,ai=new Map,Oc=null;function rm(t){let e=ur.get(t);return e?Date.now()>e.expiresAt?(ur.delete(t),null):e.value??void 0:null}function sm(t,e){if(e===void 0){ur.delete(t);return}ur.set(t,{value:e,expiresAt:Date.now()+Uc})}async function im(t){if(!t)return;if(Oc)return Oc(t);let e=[["branch","--show-current"],["rev-parse","--abbrev-ref","HEAD"]];for(let n of e)try{let{stdout:r}=await Fc("git",["-C",t,...n],{env:Qe(),timeout:tm,maxBuffer:65536}),s=r.trim();if(s&&s!=="HEAD")return s}catch{}}async function om(t){let e=rm(t);if(e!==null)return e;let n=ai.get(t);if(n)return n;let r=im(t).then(s=>(sm(t,s),s)).finally(()=>{ai.delete(t)});return ai.set(t,r),r}async function Wc(t,e,n){if(t.length===0)return;let r=Math.max(1,Math.min(e,t.length)),s=0;await Promise.all(Array.from({length:r},async()=>{for(;;){let i=s;if(s+=1,i>=t.length)return;await n(t[i])}}))}async function Gc(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await Wc(e,qc,async r=>{n.set(r,await om(r))}),n}var ci=new Map,li=new Map,Bc=null;function am(t,e){if(e===void 0){ci.delete(t);return}ci.set(t,{value:e,expiresAt:Date.now()+Uc})}async function lm(t){if(t){if(Bc)return Bc(t);for(let e=0;e<2;e+=1)try{let{stdout:n}=await Fc("git",["-C",t,"diff","HEAD","--shortstat"],{env:Qe(),timeout:nm,maxBuffer:65536}),r=n.trim();if(!r)return;let s=r.match(/(\d+) insertion/),i=r.match(/(\d+) deletion/),o=s?Number(s[1]):0,a=i?Number(i[1]):0;return o===0&&a===0?void 0:{additions:o,deletions:a}}catch{if(e===1)return}}}async function cm(t){let e=ci.get(t);if(e&&Date.now()<=e.expiresAt)return e.value;let n=li.get(t);if(n)return n;let r=lm(t).then(s=>(am(t,s),s)).finally(()=>{li.delete(t)});return li.set(t,r),r}async function jc(t){let e=[...new Set(t.filter(Boolean))],n=new Map;return await Wc(e,qc,async r=>{n.set(r,await cm(r))}),n}var zc=require("fs"),Oe=require("fs/promises"),di=require("os"),dn=require("path");var un=P.child({module:"activity-watcher"}),um=12e4,dm=5e3,fm=6e4,Vc=5;function pm(){return(0,dn.join)((0,di.homedir)(),".claude","projects")}function hm(){return(0,dn.join)((0,di.homedir)(),".codex","sessions")}async function $c(t){try{return await(0,Oe.realpath)(t)}catch{return t}}function dr(t,e){return!(!t.endsWith(".jsonl")||e==="claude"&&t.includes("/subagents/"))}var ui=class{entries=new Map;filePathIndex=new Map;metaInFlight=new Map;roots=new Map;watchers=[];pollTimers=[];rescanTimer=null;listeners=new Set;started=!1;async start(e){if(this.started)return;this.started=!0;let n=await $c(e?.claudeDir??pm()),r=await $c(e?.codexDir??hm());if(this.roots.set(n,"claude"),this.roots.set(r,"codex"),await Promise.all([this.bootstrap("claude",n),this.bootstrap("codex",r)]),this.updateGauges(),e?.usePolling){let s=e.pollingIntervalMs??100;for(let[i,o]of this.roots){let a=setInterval(()=>{this.pollScan(o,i)},s);a.unref?.(),this.pollTimers.push(a)}}else for(let[s,i]of this.roots)this.startNativeWatch(s,i);this.rescanTimer=setInterval(()=>{this.safetyRescan().catch(s=>{un.warn({error:String(s)},"activity watcher rescan failed")})},fm),this.rescanTimer.unref?.(),un.info({seeded:this.entries.size},"activity watcher started")}async stop(){if(this.started){this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);for(let e of this.pollTimers)clearInterval(e);this.pollTimers=[];for(let e of this.watchers)try{e.close()}catch{}this.watchers=[],this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}}startNativeWatch(e,n){try{let r=(0,zc.watch)(e,{recursive:!0,persistent:!0},(s,i)=>{if(!i)return;let o=(0,dn.join)(e,i.toString());dr(o,n)&&this.resolveFsEvent(n,o)});r.on("error",s=>{un.warn({error:String(s),root:e},"activity watcher error")}),this.watchers.push(r)}catch(r){un.warn({error:String(r),root:e},"failed to start native recursive watch")}}async resolveFsEvent(e,n){let r=await(0,Oe.stat)(n).catch(()=>null);if(!r){this.handleUnlink(n);return}r.isFile()&&await this.handleFsChange(n,r.mtimeMs)}async pollScan(e,n){let r=await this.walkSessionFiles(n,Vc),s=new Set,i=!1;for(let{filePath:o,mtimeMs:a}of r){if(!dr(o,e))continue;s.add(o);let l=this.filePathIndex.get(o);if(l){let u=this.entries.get(l);if(!u||a<=u.mtimeMs)continue}await this.ingestPath(e,o,Date.now(),a)&&(i=!0)}for(let[o]of this.filePathIndex)this.identifyAgent(o)===e&&(s.has(o)||(this.handleUnlink(o),i=!0));i&&(this.updateGauges(),this.notify())}identifyAgent(e){for(let[n,r]of this.roots)if(e===n||e.startsWith(`${n}/`))return r;return null}listActive(e=um){let n=Date.now(),r=n-e,s=n-dm,i=[];for(let o of this.entries.values())o.lastActivityMs<r||i.push({...o,isResponding:o.lastActivityMs>=s});return i}onActivity(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async bootstrap(e,n){let r=await this.walkSessionFiles(n,Vc);await Promise.all(r.map(async({filePath:s,mtimeMs:i})=>{dr(s,e)&&await this.ingestPath(e,s,i,i)}))}async walkSessionFiles(e,n){let r=[],s=async(i,o)=>{if(o>n)return;let a=await(0,Oe.readdir)(i,{withFileTypes:!0}).catch(()=>[]);await Promise.all(a.map(async l=>{let c=(0,dn.join)(i,l.name);if(l.isDirectory()){await s(c,o+1);return}if(!l.isFile()||!l.name.endsWith(".jsonl"))return;let u=await(0,Oe.stat)(c).catch(()=>null);u&&r.push({filePath:c,mtimeMs:u.mtimeMs})}))};return await s(e,0),r}async handleFsChange(e,n){let r=this.identifyAgent(e);if(!r||!dr(e,r))return;let s=Date.now(),i=n??s;await this.ingestPath(r,e,s,i)&&(this.updateGauges(),this.notify())}handleUnlink(e){let n=this.filePathIndex.get(e);n&&(this.filePathIndex.delete(e),this.entries.delete(n),this.updateGauges(),this.notify())}async ingestPath(e,n,r,s){let i=this.filePathIndex.get(n);if(i)return this.touchEntry(i,r,s);let o=`${e}:${n}`,a=this.metaInFlight.get(o);return a||(a=(async()=>{try{let l=await fn(n,e);if(!l)return;let c=`${e}:${l.sessionId}`,u=this.entries.get(c);if(u){u.lastActivityMs=Math.max(u.lastActivityMs,r),u.mtimeMs=Math.max(u.mtimeMs,s),u.filePath!==n&&(this.filePathIndex.delete(u.filePath),u.filePath=n),this.filePathIndex.set(n,c);return}this.entries.set(c,{agent:e,sessionId:l.sessionId,cwd:l.cwd,title:l.title,filePath:n,lastActivityMs:r,mtimeMs:s}),this.filePathIndex.set(n,c)}finally{this.metaInFlight.delete(o)}})(),this.metaInFlight.set(o,a)),await a,this.filePathIndex.has(n)}touchEntry(e,n,r){let s=this.entries.get(e);if(!s)return!1;let i=Math.max(s.lastActivityMs,n),o=Math.max(s.mtimeMs,r);return i===s.lastActivityMs&&o===s.mtimeMs?!1:(s.lastActivityMs=i,s.mtimeMs=o,!0)}async safetyRescan(){if(this.entries.size===0)return;let e=[];for(let[r,s]of this.entries)e.push((async()=>{let i=await(0,Oe.stat)(s.filePath).catch(()=>null);return i?i.mtimeMs>s.mtimeMs?this.touchEntry(r,i.mtimeMs,i.mtimeMs):!1:(this.filePathIndex.delete(s.filePath),this.entries.delete(r),!0)})());(await Promise.all(e)).some(Boolean)&&(this.updateGauges(),this.notify())}notify(){for(let e of this.listeners)try{e()}catch(n){un.warn({error:String(n)},"activity listener failed")}}updateGauges(){w.gauge("session.activity_watcher.entries",this.entries.size)}__injectEntryForTests(e){let n=`${e.agent}:${e.sessionId}`;this.entries.set(n,{...e}),this.filePathIndex.set(e.filePath,n),this.updateGauges(),this.notify()}__resetForTests(){this.started=!1,this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);for(let e of this.pollTimers)clearInterval(e);this.pollTimers=[],this.watchers=[],this.entries.clear(),this.filePathIndex.clear(),this.metaInFlight.clear(),this.roots.clear(),this.listeners.clear(),this.updateGauges()}},At=new ui;var Ze=P.child({module:"inventory"}),Xc=6e3,gm=1e4;function mm(t){return{agent:t.agent,cwd:t.cwd,sessionId:t.sessionId,confidence:"high",sessionFilePath:t.filePath,title:t.title,isResponding:t.isResponding}}async function ym(){return At.listActive().map(mm)}var Zc={listScannedSessions:mn,scanRunningSessions:ym,searchSessionContent:iu},oe=vm(),hn=null,fr=0,hr=0,pr=0,fi=0,pi=new Set;function vm(){return{scannedSessions:[],runningSessions:[],scannedAt:"",refreshedAt:0}}function Sm(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,branch:t.branch,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[...t.sources].sort(),runtime:{state:t.runtime.state,confidence:t.runtime.confidence,resumeMode:t.runtime.resumeMode,pid:t.runtime.pid,command:t.runtime.command,isResponding:t.runtime.isResponding,needsAttention:t.runtime.needsAttention},managed:t.managed,approvalMode:t.approvalMode,observedApprovalMode:t.observedApprovalMode})}function _m(t){return JSON.stringify({sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,pid:t.pid,command:t.command,confidence:t.confidence,isResponding:t.isResponding,approvalMode:t.approvalMode})}function Yc(t){return JSON.stringify({scannedSessions:t.scannedSessions.map(Sm).sort(),runningSessions:t.runningSessions.map(_m).sort()})}function bm(){for(let t of pi)try{t()}catch(e){Ze.warn({error:String(e)},"session inventory backfill listener failed")}}function pn(){w.gauge("session.inventory.external_cached_sessions",oe.scannedSessions.length),w.gauge("session.inventory.external_running_sessions",oe.runningSessions.length),w.gauge("session.inventory.backfill_inflight",hn?1:0)}function eu(t){return pi.add(t),()=>{pi.delete(t)}}function tu(){return{cachedSessions:oe.scannedSessions.length,runningSessions:oe.runningSessions.length,cacheAgeMs:oe.refreshedAt?Math.max(0,Date.now()-oe.refreshedAt):void 0,backfillInFlight:!!hn,lastBackfillDurationMs:pr||void 0,lastBackfillCompletedAt:hr?new Date(hr).toISOString():void 0,lastBackfillAppliedAt:fi?new Date(fi).toISOString():void 0}}pn();function nu(){return At.onActivity(()=>{su(Zc,Xc)})}var Tt={daemonActive:3,externalRunning:2,idle:1},Jc={high:3,medium:2,low:1};function ru(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function wm(t,e){let n=t.runtime.needsAttention?1:0,r=e.runtime.needsAttention?1:0,s=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return r-n||i-s||Tt[e.runtime.state]-Tt[t.runtime.state]||ru(t,e)}function Im(t,e){return Tt[e.state]>Tt[t.state]?e:Tt[e.state]<Tt[t.state]?t:Jc[e.confidence]>Jc[t.confidence]?e:t}function Am(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function Tm(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function xm(t,e){return e?t?!(It(e)&&!It(t)):!0:!1}function hi(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function Cm(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:{...hi()},managed:t.managed,approvalMode:t.approvalMode}}function km(t,e){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:e,lastActivityAt:e,sources:["process"],runtime:{state:"externalRunning",confidence:t.confidence,resumeMode:"resumeSession",...t.pid!==void 0?{pid:t.pid}:{},...t.command!==void 0?{command:t.command}:{},isResponding:t.isResponding},observedApprovalMode:t.approvalMode}}function Em(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver",needsAttention:t.needsAttention||void 0,isResponding:t.isResponding||void 0},managed:t.managed,approvalMode:t.approvalMode}}function Pm(t,e){for(let n of e){let r=`${n.agent}:${n.sessionId}`,s=t.get(r);if(!s){t.set(r,{...n,sources:[...n.sources],runtime:{...n.runtime}});continue}let i=xm(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=n.branch??s.branch,l=Im(s.runtime,n.runtime),c=s.sources.slice();for(let h of n.sources)c.includes(h)||c.push(h);let u=n.sources.includes("process"),d=s.sources.includes("process")&&!s.sources.includes("daemon"),f=u?s.lastActivityAt:d?n.lastActivityAt:Tm(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,branch:a,title:i,createdAt:Am(s.createdAt,n.createdAt),lastActivityAt:f,sources:c,runtime:l,managed:s.managed||n.managed,approvalMode:n.approvalMode??s.approvalMode,observedApprovalMode:n.observedApprovalMode??s.observedApprovalMode})}}function Rm(...t){let e=new Map;for(let n of t)Pm(e,n);return[...e.values()]}function Mm(t,e,n,r,s,i){let o=r?.toLowerCase(),a=t.filter(l=>{if(e&&l.agent!==e||n&&l.cwd!==n)return!1;if(o){let c=(l.title??"").toLowerCase(),u=(l.cwd??"").toLowerCase(),d=i?.[l.sessionId]?.toLowerCase()??"",f=c.includes(o)||u.includes(o)||(d?d.includes(o):!1),h=s?.has(l.sessionId)??!1;if(!f&&!h)return!1}return!0});return r&&Ze.info({total:t.length,filtered:a.length,search:r,contentMatchIds:s?.size??0},"filter applied"),a}function Lm(t,e){if(!e)return 0;let n=0,r=t.length;for(;n<r;){let s=n+r>>1,i=t[s];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?r=s:n=s+1}if(n>0){let s=t[n-1];if(s.lastActivityAt===e.lastActivityAt&&s.sessionId===e.sessionId)return n}return 0}function Kc(t,e,n,r,s,i,o,a){let l=i?1/0:Math.max(1,e||50),c=Rm(t.sessionRecords.map(Cm),t.scannedSessions,t.runningSessions.map(b=>km(b,t.scannedAt)),t.activeSessions.map(Em)),u=t.deletedSessionIds?.size?c.filter(b=>!t.deletedSessionIds?.has(b.sessionId)):c,d=Mm(u,r,s,i,o,a),f=d.filter(b=>b.runtime.state!=="idle"||b.managed).sort(wm),h=d.filter(b=>b.runtime.state==="idle"&&!b.managed).sort(ru),g=Lm(h,n),p=h.slice(g,g+l),v=g+p.length<h.length&&p.length>0?{lastActivityAt:p[p.length-1].lastActivityAt,sessionId:p[p.length-1].sessionId}:void 0;return{sessions:n?p:[...f,...p],nextCursor:v}}async function Qc(t){if(t.sessions.length===0)return t;let e=t.sessions.map(o=>o.cwd),[n,r]=await Promise.all([Gc(e),jc(e)]),s=!1,i=t.sessions.map(o=>{let a=n.get(o.cwd),l=r.get(o.cwd);return o.branch===a&&o.diffStat===l?o:(s=!0,{...o,branch:a,diffStat:l})});return s?{...t,sessions:i}:t}function gn(t,e,n,r,s){return new Promise(i=>{let o=Date.now(),a=!1,l=null,c=u=>{a||(a=!0,l&&(clearTimeout(l),l=null),i(u))};l=setTimeout(()=>{if(a)return;let u=Array.isArray(s)&&s.length>0;Ze.warn({source:t,timeoutMs:r,durationMs:Date.now()-o,partial:u?s.length:0},u?"session inventory source timed out, using partial results":"session inventory source timed out, using fallback"),c(u?s:n)},r),typeof l=="object"&&"unref"in l&&l.unref(),e().then(u=>{c(u)}).catch(u=>{a||Ze.warn({source:t,error:String(u)},"session inventory source failed, using fallback"),c(n)})})}function Nm(t=Date.now()){return oe.refreshedAt===0||t-oe.refreshedAt>=gm}async function Om(t,e){let n=new Date().toISOString(),r=[],[s,i]=await Promise.all([gn("scanner.sessions",()=>t.listScannedSessions(void 0,void 0,r),[],e,r),gn("process.running_sessions",()=>t.scanRunningSessions(),[],e)]);return{scannedSessions:s,runningSessions:i,scannedAt:n,refreshedAt:Date.now()}}function su(t,e){if(hn)return;let n=fr,r=w.startTimer("session.inventory.backfill_latency_ms");hn=Om(t,e).then(s=>{if(n!==fr)return;let i=Yc(oe);oe=s;let o=Yc(s),a=r();pr=a,hr=Date.now(),pn(),i!==o&&(fi=Date.now(),w.increment("session.inventory.backfill_applied"),Ze.info({durationMs:a,scanned:s.scannedSessions.length,running:s.runningSessions.length},"session inventory external backfill applied"),bm())}).catch(s=>{n===fr&&(pr=r(),hr=Date.now(),pn(),Ze.warn({error:String(s),durationMs:pr},"session inventory external backfill failed"))}).finally(()=>{n===fr&&(hn=null,pn())}),pn()}async function gr(t){let e={...Zc,...t.loaders??{}},n=Math.max(250,t.sourceTimeoutMs??Xc);if(!t.search){let u=w.startTimer("session.inventory.fast_path_latency_ms");Nm()&&su(e,n);let d=oe,f=Kc({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:d.scannedSessions,runningSessions:d.runningSessions,scannedAt:d.scannedAt||new Date().toISOString(),deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,void 0,void 0,t.customTitles);if(t.skipGitMetadata)return u(),f;let h=await Qc(f);return u(),h}let r=[],s=new Date().toISOString(),i=t.search,[o,a,l]=await Promise.all([gn("scanner.sessions",()=>e.listScannedSessions(t.agent,t.cwd,r),[],n,r),gn("process.running_sessions",()=>e.scanRunningSessions(),[],n),gn("scanner.search_content",()=>e.searchSessionContent(i,t.agent),void 0,n)]);Ze.info({search:t.search,contentMatches:l?.size??0,scanned:o.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results");let c=Kc({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:o,runningSessions:a,scannedAt:s,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,i,l,t.customTitles);return t.skipGitMetadata?c:Qc(c)}var Be=P.child({module:"scanner"});function du(t){let e=new Map;return{get(n){let r=e.get(n);if(r){if(Date.now()>r.expiresAt){e.delete(n);return}return r.value}},set(n,r){e.set(n,{value:r,expiresAt:Date.now()+t})},clear(){e.clear()}}}var fu=3e4,vi=du(fu),Si=du(fu),gi=new Map,mi=new Map,xt=24;function yr(){vi.clear(),Si.clear()}function pu(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function Ct(t,e,n){if(t.length===0)return[];let r=Math.max(1,Math.min(e,t.length)),s=new Array(t.length),i=0;return await Promise.all(Array.from({length:r},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;s[o]=await n(t[o],o)}})),s}function*hu(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
93
+ `,n);s===-1&&(s=t.length);let i=t.substring(n,s);n=s+1,!(i.length===0||i.trim().length===0)&&(yield i,r+=1)}}var yi=512*1024,ou=256*1024;async function gu(t,e){if(e<=yi)return(0,R.readFile)(t,"utf-8");let n=await(0,R.open)(t,"r");try{let r=Buffer.alloc(yi),{bytesRead:s}=await n.read(r,0,yi,0);return r.toString("utf-8",0,s)}finally{await n.close()}}async function Bm(t,e){if(e<=ou)return(0,R.readFile)(t,"utf-8");let n=await(0,R.open)(t,"r");try{let r=Math.max(0,e-ou),s=Buffer.alloc(e-r),{bytesRead:i}=await n.read(s,0,s.length,r);return s.toString("utf-8",0,i)}finally{await n.close()}}function au(t){switch(t){case"plan":return"plan";case"acceptEdits":return"acceptEdits";case"bypassPermissions":return"autoApprove";case"default":return"normal";default:return}}function Dm(t){let e=typeof t?.approval_policy=="string"?t.approval_policy:"",n=t?.sandbox_policy,r=typeof n?.type=="string"?n.type:"",s=Array.isArray(n?.writable_roots)?n.writable_roots:null;if(e==="never"&&r==="danger-full-access")return"autoApprove";if(e==="on-request"&&r==="workspace-write")return s?.length?"normal":"plan"}function Hm(t){return t?.type==="permission-mode"?au(t.permissionMode):au(t?.permissionMode)}function Fm(t){if(t?.type==="turn_context")return Dm(t.payload)}async function mu(t,e,n){let r,s=await Bm(t,n);for(let i of s.split(`
94
+ `)){if(!i.trim())continue;let o;try{o=JSON.parse(i)}catch{continue}let a=e==="claude"?Hm(o):Fm(o);a&&(r=a)}return r}function Ii(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").join(""):""}function yu(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?Ii(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function vr(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>!e||typeof e!="object"||e.type!=="text"?"":typeof e.text=="string"?e.text:"").join(""):""}var Um=["<task-notification>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","<system-reminder>","<environment_context>","# AGENTS.md instructions for "];function qm(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?Um.some(r=>n.startsWith(r)):!1}function Sr(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=vr(t.message.content);return qm(t,e)?"":e}function Wm(t){return Array.isArray(t)&&t.some(e=>e&&typeof e=="object"&&e.type==="tool_result")}function Gm(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object"||e.type!=="tool_result")return"";let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.map(r=>!r||typeof r!="object"?"":typeof r.text=="string"?r.text:typeof r.content=="string"?r.content:"").filter(Boolean).join(`
96
95
  `):""}).filter(Boolean).join(`
97
- `):""}function _A(t){let e=yA(t?.message?.content);if(/\[Request interrupted by user(?: for tool use)?\]/i.test(e))return!0;let n=t?.toolUseResult;return!!(n&&typeof n=="object"&&n.interrupted===!0||typeof n=="string"&&/\[Request interrupted by user(?: for tool use)?\]/i.test(n))}function Dp(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function Fs(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,observedApprovalMode:t.approvalMode,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:Oa()}}function Ws(t,e){let n=(0,Q.basename)(e,".jsonl");return t==="claude"?n||null:n.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i)?.[1]??null}async function SA(t,e){let n=await Lp(t,e),r=Mp(n,64),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(!s&&typeof u.cwd=="string"&&(s=u.cwd),!i&&typeof u.sessionId=="string"&&(i=u.sessionId),o||(o=Nt([u.customTitle,u.summary])),!l){let d=$s(u),f=Nt([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||Ws("claude",t)||(0,Q.basename)(t,".jsonl"),cwd:s,title:o??l??Nt([],a),approvalMode:await Np(t,"claude",e)}:null}async function vA(t,e){let n=await Lp(t,e),r=Mp(n,96),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(s||(s=u.payload?.cwd??u.cwd??""),i||(i=u.payload?.id??u.id??""),o||(o=Nt([u.payload?.title,u.title])),!l){let d=Op(u),f=d&&!Dp(d)?Nt([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||Ws("codex",t)||(0,Q.basename)(t,".jsonl"),cwd:s,title:o??l??Nt([],a),approvalMode:await Np(t,"codex",e)}:null}async function ur(t,e){let n=await(0,J.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await SA(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,approvalMode:i.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await vA(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,approvalMode:s.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function xp(t,e){let n=(0,Q.join)((0,tt.homedir)(),".claude","projects");try{let r;t?r=[Pp(t)]:r=(await(0,J.readdir)(n,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name);let s=[];for(let l of r){let c=(0,Q.join)(n,l),u=await(0,J.readdir)(c).catch(()=>[]);for(let d of u)d.endsWith(".jsonl")&&s.push((0,Q.join)(c,d))}let i=await yn(s,mn,async l=>{let c=await(0,J.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await yn(i,mn,async l=>{let c=await ur(l.path,"claude");return c&&e&&e.push(Fs(c)),c})).filter(l=>l!==null).map(l=>Fs(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return mt.warn({error:String(r)},"failed to list claude sessions"),[]}}async function Cp(t,e){let n=(0,Q.join)((0,tt.homedir)(),".codex","sessions");try{let r=await(0,J.readdir)(n).catch(()=>[]),s=[];for(let l of r){let c=(0,Q.join)(n,l),u=await(0,J.readdir)(c).catch(()=>[]);for(let d of u){let f=(0,Q.join)(c,d),p=await(0,J.readdir)(f).catch(()=>[]);for(let g of p){let h=(0,Q.join)(f,g),_=await(0,J.readdir)(h).catch(()=>[]);for(let w of _)w.endsWith(".jsonl")&&s.push((0,Q.join)(h,w))}}}let i=await yn(s,mn,async l=>{let c=await(0,J.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await yn(i,mn,async l=>{let c=await ur(l.path,"codex");return c&&e&&(!t||c.cwd===t)&&e.push(Fs(c)),c})).filter(l=>l!==null).filter(l=>!t||l.cwd===t).map(l=>Fs(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return mt.warn({error:String(r)},"failed to list codex sessions"),[]}}async function pr(t,e,n){let s=`list:${(0,tt.homedir)()}:${t??"all"}:${e??""}`,i=Fa.get(s);if(i)return i;let o=Da.get(s);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await xp(e,n);else if(t==="codex")l=await Cp(e,n);else{let[c,u]=await Promise.all([xp(e,n),Cp(e,n)]);l=[...c,...u].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return Fa.set(s,l),l})();return Da.set(s,a),a.finally(()=>Da.delete(s)),a}async function Ap(t,e){let r=`search:${(0,tt.homedir)()}:${t}:${e??"all"}`,s=Ua.get(r);if(s)return s;let i=Ha.get(r);if(i)return i;let o=(async()=>{let a=new Set,l=t.toLowerCase();async function c(){let d=(0,Q.join)((0,tt.homedir)(),".claude","projects");try{let f=await(0,J.readdir)(d,{withFileTypes:!0}),p=[];for(let h of f){if(!h.isDirectory())continue;let _=(0,Q.join)(d,h.name),w=await(0,J.readdir)(_).catch(()=>[]);for(let E of w)E.endsWith(".jsonl")&&p.push((0,Q.join)(_,E))}let g=await yn(p,mn,h=>Tp(h,l,"claude"));for(let h of g)h&&a.add(h)}catch(f){mt.warn({error:String(f)},"failed to search claude files")}}async function u(){let d=(0,Q.join)((0,tt.homedir)(),".codex","sessions");try{let f=[];async function p(h){let _=await(0,J.readdir)(h,{withFileTypes:!0}).catch(()=>[]);for(let w of _){let E=(0,Q.join)(h,w.name);w.isDirectory()?await p(E):w.name.endsWith(".jsonl")&&f.push(E)}}await p(d);let g=await yn(f,mn,h=>Tp(h,l,"codex"));for(let h of g)h&&a.add(h)}catch(f){mt.warn({error:String(f)},"failed to search codex files")}}return e==="claude"?await c():e==="codex"?await u():await Promise.all([c(),u()]),Ua.set(r,a),a})();return Ha.set(r,o),o.finally(()=>Ha.delete(r)),o}async function Tp(t,e,n){let r=(0,$a.createReadStream)(t,{encoding:"utf-8"}),s=(0,Wa.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?wA:bA,o="",a=!1;try{for await(let l of s){if(!l.trim())continue;let c;try{c=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof c.sessionId=="string"&&(o=c.sessionId):o=c.payload?.id??c.id??""),!a){let u=i(c);u&&u.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{s.close(),r.destroy()}return a?o||Ws(n,t):null}function wA(t){return t?.type==="user"&&t.message?.role==="user"?$s(t):t?.type==="assistant"&&t.message?.role==="assistant"?qs(t.message.content):""}function bA(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return Ga(t.payload.content)}let e=Op(t);return e||""}async function qa(t,e){let n=(0,$a.createReadStream)(t,{encoding:"utf-8"}),r=(0,Wa.createInterface)({input:n,crlfDelay:1/0});try{for await(let s of r){if(!s.trim())continue;let i;try{i=JSON.parse(s)}catch{continue}if(e(i))break}}finally{r.close(),n.destroy()}}async function Hp(t,e){let n=(0,Q.join)((0,tt.homedir)(),".claude","projects"),r=e?Pp(e):null,s=await(0,J.readdir)(n).catch(()=>[]),i=r?[r,...s.filter(o=>o!==r)]:s;for(let o of i){let a=(0,Q.join)(n,o,`${t}.jsonl`);if((await(0,J.stat)(a).catch(()=>null))?.isFile())return a}return null}async function Bp(t,e,n){if(e==="claude")return Hp(t,n);let r=(0,Q.join)((0,tt.homedir)(),".codex","sessions");return Up(r,t)}function AA(t){if(t?.type==="user"&&t.message?.role==="user")return mA(t.message.content)?{kind:"toolResult",..._A(t)?{interrupted:!0}:{}}:$s(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=qs(t.message.content),n=t.message?.stop_reason;return{kind:"assistant",stopReason:typeof n=="string"?n:n??null,...e?{text:e}:{}}}return t?.type==="system"&&t.subtype==="stop_hook_summary"?{kind:"stopHook"}:null}function EA(t){if(!t)return{};if(t.kind==="stopHook")return{};if(t.kind==="assistant"){let e=t.stopReason==null||t.stopReason==="tool_use";return{...e?{isResponding:!0}:{},...e&&t.text?{partialReplyText:t.text}:{}}}return t.kind==="toolResult"&&t.interrupted?{}:{isResponding:!0}}async function Fp(t,e){if(e!=="claude")return{};let n=null;try{await qa(t,r=>{let s=AA(r);s&&(n=s)})}catch(r){return r.code!=="ENOENT"&&mt.warn({filePath:t,error:String(r)},"failed to read session runtime hints"),{}}return EA(n)}async function ja(t,e,n){let r=await Bp(t,e,n);return r?Fp(r,e):{}}async function gr(t,e,n){let r=[],s=(i,o)=>{if(o?.coalesceConsecutiveAssistant&&i.role==="assistant"&&r[r.length-1]?.role==="assistant"){r[r.length-1]=i;return}r.push(i)};if(e==="claude")try{let i=await Hp(t,n);i&&await qa(i,o=>{if(o.type==="user"&&o.message?.role==="user"){let a=$s(o);a&&s({role:"user",content:a})}else if(o.type==="assistant"&&o.message?.role==="assistant"){let a=qs(o.message.content);a&&s({role:"assistant",content:a})}})}catch(i){mt.warn({error:String(i)},"failed to read claude session history")}else if(e==="codex")try{let i=await Bp(t,e,n);i&&await qa(i,o=>{if(o.type!=="response_item"||o.payload?.type!=="message")return;let a=o.payload.role;if(a!=="user"&&a!=="assistant")return;let l=Ga(o.payload.content);l&&(a==="user"&&Dp(l)||s({role:a,content:l},{coalesceConsecutiveAssistant:!0}))})}catch(i){mt.warn({error:String(i)},"failed to read codex session history")}return r}async function Up(t,e){try{let n=await(0,J.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,Q.join)(t,r.name);if(r.isDirectory()){let i=await Up(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){mt.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var qp=require("child_process");var $p=require("util");var pC=(0,$p.promisify)(qp.execFile),gC=K.child({module:"process-scanner"});var IA=null;function Gs(){IA=null}var _n=require("fs"),Vp=require("path");var xA=500,Wp=200;function Gp(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=Wp?e:e.slice(-Wp)}function CA(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n!="string"||n.length===0||e.includes(n)||e.push(n);return e}function TA(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",r=typeof e.toolName=="string"?e.toolName:"",s=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!r||!s)return;let o=e.approvalContext;return o&&typeof o=="object"&&!Array.isArray(o)&&o.provider==="codex"&&typeof o.kind=="string"&&typeof o.rpcId=="number"?{requestId:n,toolName:r,input:i,description:s,approvalContext:{provider:"codex",kind:o.kind,rpcId:o.rpcId,...typeof o.questionId=="string"?{questionId:o.questionId}:{},...typeof o.approveLabel=="string"?{approveLabel:o.approveLabel}:{},...typeof o.denyLabel=="string"?{denyLabel:o.denyLabel}:{}}}:{requestId:n,toolName:r,input:i,description:s}}function jp(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:Gp(t.acceptedClientMessageIds),interruptedClientMessageIds:Gp(t.interruptedClientMessageIds),pendingApproval:TA(t.pendingApproval)}}function RA(t){if(Array.isArray(t))return{records:t.map(jp),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(jp):[],deletedSessionIds:CA(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var js=class{records;deletedSessionIds;debounceTimer=null;constructor(){let e=this.loadFromDisk();this.records=e.records,this.deletedSessionIds=new Set(e.deletedSessionIds)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}find(e){return this.records.find(n=>n.sessionId===e)}isDeleted(e){return this.deletedSessionIds.has(e)}upsert(e){this.deletedSessionIds.delete(e.sessionId);let n=this.records.findIndex(r=>r.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}remove(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.add(e),this.scheduleSave()}flushSync(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.saveToDisk()}scheduleSave(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.saveToDisk()},xA)}loadFromDisk(){try{let e=(0,_n.readFileSync)(ns,"utf-8");return RA(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,_n.mkdirSync)((0,Vp.dirname)(ns),{recursive:!0}),(0,_n.writeFileSync)(ns,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var Sn=require("path"),zp=require("os");function Vs(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,Sn.join)((0,zp.homedir)(),t.slice(2)):t}function kA(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let r=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return r&&(e=r[1]??e),e}function Va(t,e){let n=Vs(kA(t));if(!n||(0,Sn.isAbsolute)(n))return n;let r=Vs(e??"");return r?(0,Sn.resolve)(r,n):n}var Yp={approvalRequestV1:"vibelet.approvalRequest.v1"};var vn=require("fs"),Kp=require("path");function PA(t){return!!(t&&typeof t=="object"&&typeof t.deviceId=="string"&&typeof t.pushToken=="string"&&t.platform==="expo"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"&&(typeof t.lastSentAt=="string"||typeof t.lastSentAt>"u"))}function MA(t){try{let e=(0,vn.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(PA):[]}catch{return[]}}function mr(t,e){(0,vn.mkdirSync)((0,Kp.dirname)(t),{recursive:!0}),(0,vn.writeFileSync)(t,JSON.stringify(e,null,2)+`
98
- `,"utf8")}var zs=class{constructor(e=Ed){this.pushSubscriptionsPath=e;this.records=MA(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}count(){return this.records.length}register(e,n){let r=new Date().toISOString(),s=this.records.find(o=>o.deviceId===e),i={deviceId:e,pushToken:n,platform:"expo",createdAt:s?.createdAt??r,updatedAt:r,...s?.lastSentAt?{lastSentAt:s.lastSentAt}:{}};this.records=[i,...this.records.filter(o=>o.deviceId!==e&&o.pushToken!==n)],mr(this.pushSubscriptionsPath,this.records)}unregister(e,n){let r=this.records.filter(s=>!(s.deviceId===e&&s.pushToken===n));return r.length===this.records.length?!1:(this.records=r,mr(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(r=>r.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,mr(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),r=new Date().toISOString(),s=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=r,s=!0);s&&mr(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],mr(this.pushSubscriptionsPath,this.records)}};var ve=K.child({module:"push"}),LA="https://exp.host/--/api/v2/push/send",NA="https://exp.host/--/api/v2/push/getReceipts",OA=[0,1e3,3e3],yr=new zs;function DA(t){return!!(t&&typeof t=="object"&&typeof t.daemonId=="string"&&typeof t.canonicalHost=="string"&&typeof t.sessionId=="string"&&(t.agent==="claude"||t.agent==="codex")&&(t.eventType==="reply_ready"||t.eventType==="approval_request")&&(typeof t.requestId>"u"||typeof t.requestId=="string"))}function HA(t){return new Promise(e=>{setTimeout(e,t)})}function Jp(t){return t==="DeviceNotRegistered"}function BA(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],r=[];for(let[s,i]of t.data.entries()){let o=e[s];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}r.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:r}}function FA(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[r,s]of t.data.entries()){let i=e[r];!i||!s||s.status!=="ok"||typeof s.id!="string"||s.id.length===0||n.set(s.id,i)}return n}function UA(t,e){let n=[],r=[],s=t.data;for(let[i,o]of e.entries()){let a=s?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&r.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:r}}async function qA(t,e,n,r){let s=new Map(t);for(let i of OA){if(s.size===0)return;i>0&&await n(i);let o;try{o=await e(NA,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...s.keys()]})})}catch(u){ve.error({error:String(u),count:s.size},"push receipt request failed");return}if(!o.ok){ve.error({status:o.status,statusText:o.statusText,count:s.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){ve.error({count:s.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:c}=UA(a,s);for(let{token:u,receipt:d}of c){let f=d.details?.error;if(ve.error({token:u,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),Jp(f)){let p=r.unregisterToken(u);ve.info({token:u,errorCode:f,removed:p},"push token removed after receipt rejection")}}s=new Map(l.map(u=>[u,s.get(u)]))}s.size>0&&ve.warn({pendingReceipts:s.size},"push receipts still pending after polling")}function $A(t){let e=t?.pushStore??yr,n=t?.fetchImpl??globalThis.fetch,r=t?.sleepImpl??HA;return async function(i,o,a){let l=e.listTokens();if(l.length===0)return;let c=l.map(u=>({to:u,sound:"default",title:i,body:o,data:a,badge:1,...DA(a)&&a.eventType==="approval_request"?{categoryId:Yp.approvalRequestV1}:{}}));try{let u=await n(LA,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok){ve.error({status:u.status,statusText:u.statusText},"push send failed");return}let d=await u.json().catch(()=>null);if(!d){ve.error({count:c.length},"push send returned unreadable response");return}let{successfulTokens:f,ticketErrors:p}=BA(d,l),g=FA(d,l);for(let{token:h,ticket:_}of p){let w=_.details?.error;if(ve.error({token:h,message:_.message,details:_.details,ticketStatus:_.status},"push ticket rejected"),Jp(w)){let E=e.unregisterToken(h);ve.info({token:h,errorCode:w,removed:E},"push token removed after ticket rejection")}}f.length>0&&(ve.debug({count:f.length},"push sent"),e.markSent(f)),g.size>0&&await qA(g,n,r,e)}catch(u){ve.error({error:String(u)},"push send error")}}}function za(t,e){yr.register(t,e),ve.info({deviceId:t,token:e,total:yr.count()},"push token registered")}function Ya(t,e){let n=yr.unregister(t,e);ve.info({deviceId:t,token:e,total:yr.count(),removed:n},"push token unregistered")}var Ys=$A();var T=K.child({module:"manager"}),WA="Done.",GA="Approval required",Qp=180,wn=200;function nt(...t){let e=[];for(let n of t)if(n?.length)for(let r of n)!r||e.includes(r)||(e.push(r),e.length>wn&&e.splice(0,e.length-wn));return e}function Ks(t){return t?.length?{acceptedClientMessageIds:nt(t)}:{}}function Ve(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:nt(t.acceptedClientMessageIds),interruptedClientMessageIds:nt(t.interruptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,managed:t.managed,isResponding:t.isResponding||void 0}}function Xp(t){t.managed||(t.managed=!0)}function Zp(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&us(e)}function eg(t,e,n){return{sessionId:t,agent:e,...n}}function jA(t){return t.startsWith(Eo)}function tg(t){return t?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}:{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Denied from Vibelet"}}}var Js=class{constructor(e=Ys){this.pushSender=e;this.removeInventoryBackfillListener=_p(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new js;idleSweepInterval=null;globalClients=new Set;inventoryVersion=0;removeInventoryBackfillListener;startIdleSweep(){C.idleTimeoutMs<=0&&C.turnStallTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),6e4),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=Date.now(),n=C.idleTimeoutMs,r=C.turnStallTimeoutMs;if(n<=0&&r<=0)return;let s=3600*1e3;for(let[i,o]of this.sessions){if(!o.active&&!o.driver){if(o.clients.size===0){let l=e-o.lastActivityTs;l>=s&&(T.info({sessionId:o.sessionId,inactiveMs:l},"removing inactive session from memory"),R.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(o),this.sessions.delete(i))}continue}if(!o.active||!o.driver)continue;let a=e-o.lastActivityTs;if(o.isResponding){if(r<=0||o.pendingApproval||a<r)continue;T.warn({sessionId:o.sessionId,agent:o.agent,inactiveMs:a,turnStallTimeoutMs:r},"stopping stalled driver"),R.increment("driver.stall_timeout",{agent:o.agent}),k.emit("driver.stall_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),this.resolvePendingClaudeHookApprovals(o),o.driver.stop(),o.active=!1,o.driver=null,o.isResponding=!1,o.currentReplyText="",this.updateGauges(),this.broadcast(o.sessionId,{type:"error",sessionId:o.sessionId,message:`Agent stopped responding for over ${Math.ceil(r/1e3)}s. Send a new message to continue.`}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated");continue}o.pendingApproval||n<=0||a<n||(T.info({sessionId:o.sessionId,agent:o.agent,idleMs:a,timeoutMs:n},"stopping idle driver"),R.increment("driver.idle_timeout",{agent:o.agent}),k.emit("driver.idle_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),o.driver.stop(),o.active=!1,o.driver=null,this.updateGauges(),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"))}}bindDriverLifecycle(e,n,r,s){let i=e.driver;i?.onMessage(o=>{if(e.driver!==i){T.info({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"ignoring stale driver message");return}if(T.debug({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"driver message received"),o.type!=="response"&&"sessionId"in o&&o.sessionId&&o.sessionId!==e.sessionId&&!this.sessions.has(o.sessionId)&&this.remapSessionId(e,o.sessionId,s),(o.type==="session.done"||o.type==="session.interrupted")&&(e.isResponding=!1,o.type==="session.interrupted"&&this.markLatestAcceptedClientMessageInterrupted(e),(o.type==="session.interrupted"||!Zp(e))&&(e.pendingApproval=void 0)),o.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(o.requestId,!0)??!1){k.emit("approval.response",{sessionId:e.sessionId,requestId:o.requestId,approved:!0}),e.pendingApproval=void 0,e.isResponding=!0,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated");return}T.warn({sessionId:e.sessionId,requestId:o.requestId},"failed to auto-approve codex request; falling back to pending approval flow")}e.isResponding=!1,e.pendingApproval={requestId:o.requestId,toolName:o.toolName,input:o.input,description:o.description,...o.approvalContext?{approvalContext:o.approvalContext}:{}},this.pushSender(GA,this.buildPushBody(`${e.title||e.sessionId}: ${o.description||o.toolName}`),{sessionId:e.sessionId,agent:e.agent,requestId:o.requestId,eventType:"approval_request"})}n==="claude"&&o.type==="approval.request"&&us(o.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[o.requestId]={message:e.lastUserMessage,toolName:o.toolName}:T.warn({sessionId:e.sessionId,requestId:o.requestId},"missing lastUserMessage for synthetic approval retry")),this.touchSession(e.sessionId,o.type!=="text.delta"),(o.type==="approval.request"||o.type==="session.done"||o.type==="session.interrupted")&&this.noteInventoryChanged("session_updated"),this.broadcast(e.sessionId,o),(o.type==="session.done"||o.type==="session.interrupted")&&e.bufferedPrompts.length>0&&this.flushBufferedPrompt(e)}),i?.onExit?.(o=>{if(e.driver!==i){T.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"ignoring stale driver exit");return}T.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"driver exited"),k.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:o}),R.increment("driver.exit",{agent:n,abnormal:o&&o!==0?"true":"false"});let a=!!(e.pendingApproval&&(e.agent==="codex"||o===0&&Zp(e)));this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",a||(e.pendingApproval=void 0),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated")})}remapSessionId(e,n,r){if(!n||n===e.sessionId)return;let s=this.sessions.get(n);if(s&&s!==e){T.warn({oldSessionId:e.sessionId,newSessionId:n},"skipping session ID remap because target already exists");return}let i=e.sessionId;T.info({oldSessionId:i,newSessionId:n},"session ID updated"),this.store.remove(i),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert(Ve(e)),this.noteInventoryChanged("session_remapped"),r&&this.reply(r,`id_update_${Date.now()}`,!0,{sessionId:n,oldSessionId:i})}flushBufferedPrompt(e,n=!1){if(!e.driver||!e.active||e.startupInProgress||e.pendingApproval||!n&&e.isResponding)return!1;let r=e.bufferedPrompts.shift();return r?(e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=r,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),e.driver.sendPrompt(r,e.model),!0):!1}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let r=e.driver,s=e.sessionId,i=e.startupToken,o=R.startTimer("driver.spawn");(async()=>{try{let a=await r.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(s)!==e||e.startupToken!==i||e.driver!==r){T.info({pendingSessionId:s,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,T.info({pendingSessionId:s,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==s&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(s)!==e||e.startupToken!==i){T.info({pendingSessionId:s,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1,e.bufferedPrompts=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),T.error({sessionId:s,cwd:e.cwd,error:String(a)},"async codex createSession error"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to start Codex session: ${String(a)}`})}})()}configureDriverBeforeStart(e,n,r,s){if(e==="codex"&&n instanceof Xn&&s&&n.setModel(s),e!=="claude"||!(n instanceof Qn))return;let i=r??(0,Ka.randomUUID)().replace(/-/g,"");return n.configureHookBridge(C.port,i),i}registerClaudeHookSession(e){e.agent!=="claude"||!e.claudeHookSecret||this.claudeHookSessions.set(e.claudeHookSecret,e)}unregisterClaudeHookSession(e){if(e.agent!=="claude"||!e.claudeHookSecret)return;this.claudeHookSessions.get(e.claudeHookSecret)===e&&this.claudeHookSessions.delete(e.claudeHookSecret)}resolvePendingClaudeHookApprovals(e,n=Jn){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&jA(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let r=this.resolveClaudeHookSession(e);return r?(this.touchSession(r.sessionId),!0):(T.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let r=this.resolveClaudeHookSession(e);if(!r||r.agent!=="claude"||!r.active)return T.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),Jn;if(r.approvalMode==="autoApprove")return tg(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return Jn;let o=n.tool_input??n.toolInput,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},l=typeof n.tool_use_id=="string"?n.tool_use_id:typeof n.toolUseId=="string"?n.toolUseId:"",c=`${Eo}${l.trim()||(0,Ka.randomUUID)()}`,u=r.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${i}.`,f,p=new Promise(g=>{f=g});return r.pendingClaudeHookApprovals.set(c,{requestId:c,promise:p,resolve:g=>{r.pendingClaudeHookApprovals.delete(c),f(g)}}),r.pendingApproval={requestId:c,toolName:i,input:a,description:d},k.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:i}),this.touchSession(r.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(r.sessionId,{type:"approval.request",sessionId:r.sessionId,requestId:c,toolName:i,input:a,description:d}),p}async resolveReconnectSession(e,n,r){if(this.isDeletedSession(e))return;let s=new Date().toISOString(),i=r?.agent,o=r?.cwd??"",a=r?.approvalMode,l=r?.pendingApproval,c=r?.title??"",u=r?.createdAt??s,d=r?.lastActivityAt??s,f=nt(r?.acceptedClientMessageIds),p=nt(r?.interruptedClientMessageIds),g=r?.isResponding,h=r?"memory":"client",_=this.store.find(e);if(_)i=_.agent,o=_.cwd||o,a=_.approvalMode??a,l=_.pendingApproval??l,c=_.title||c,u=_.createdAt||u,d=_.lastActivityAt||d,f=nt(_.acceptedClientMessageIds,f),p=nt(_.interruptedClientMessageIds,p),h="record";else if(!r){let E=(await pr(n??i)).find(L=>L.sessionId===e);E&&(i=E.agent,o=E.cwd||o,c=E.title??c,u=E.createdAt,d=E.lastActivityAt,g=E.runtime.isResponding??g,h="scanner")}if(!i&&n&&(i=n,h=r?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,pendingApproval:l,title:c,createdAt:u,lastActivityAt:d,acceptedClientMessageIds:f,interruptedClientMessageIds:p,source:h,managed:r?.managed??_?.managed,isResponding:g||void 0}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let r of this.sessions.values()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(eg(r.sessionId,r.agent,r.pendingApproval)))}for(let r of this.store.getAll()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(eg(r.sessionId,r.agent,r.pendingApproval)))}return e}restoreDriverPendingApproval(e,n){n&&e.restorePendingApproval?.(n)}async reviveSessionForApproval(e){if(e.driver)return!0;if(!e.pendingApproval||e.agent!=="codex")return!1;let n=this.createDriver(e.agent),r=this.configureDriverBeforeStart(e.agent,n,e.claudeHookSecret);return await n.start(e.cwd,e.sessionId,e.approvalMode),this.restoreDriverPendingApproval(n,e.pendingApproval),e.driver=n,e.active=!0,e.isResponding=!1,e.currentReplyText="",e.startupInProgress=!1,e.bufferedPrompts=e.bufferedPrompts??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=r??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert(Ve(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),!0}buildPushBody(e){let n=e.replace(/\s+/g," ").trim();return n?n.length<=Qp?n:`${n.slice(0,Math.max(1,Qp-3)).trimEnd()}...`:WA}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}touchSession(e,n=!0){let r=new Date().toISOString(),s=this.sessions.get(e);if(s){s.lastActivityAt=r,s.lastActivityTs=Date.now(),n&&this.store.upsert(Ve(s));return}let i=this.store.find(e);i&&this.store.upsert({...i,lastActivityAt:r})}updateGauges(){let e=0;for(let n of this.sessions.values())n.active&&e++;R.gauge("session.active",e)}activeSessionSnapshots(){let e=[];for(let n of this.sessions.values())n.sessionId.startsWith("pending_")||n.active&&e.push({sessionId:n.sessionId,agent:n.agent,cwd:n.cwd,approvalMode:n.approvalMode,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,...n.pendingApproval?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return pr(e,n)}async handle(e,n){switch(T.debug({action:n.action},"handling client message"),n.action){case"session.create":await this.createSession(e,n.id,n.agent,n.cwd,n.approvalMode,n.continueSession,n.model);break;case"session.resume":await this.resumeSession(e,n.id,n.sessionId,n.agent);break;case"session.send":await this.sendMessage(e,n.id,n.sessionId,n.message,n.agent,n.clientMessageId,n.images,n.model);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.stop":this.stopSession(e,n.id,n.sessionId);break;case"session.delete":this.deleteSession(e,n.id,n.sessionId);break;case"session.history":await this.sendHistory(e,n.id,n.sessionId,n.agent);break;case"reconnect.snapshot":await this.sendReconnectSnapshot(e,n.id,n.agent,n.cwd,n.search,n.activeSessionId,n.activeAgent,n.customTitles);break;case"sessions.list":await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor,n.customTitles);break}}addGlobalClient(e){this.globalClients.add(e)}removeClient(e){this.globalClients.delete(e);for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep(),this.removeInventoryBackfillListener(),this.globalClients.clear();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),e.driver?.stop()}catch(n){T.error({sessionId:e.sessionId,agent:e.agent,error:String(n)},"failed to stop session on shutdown")}e.active=!1,e.driver=null,e.clients.clear(),this.unregisterClaudeHookSession(e)}this.claudeHookSessions.clear(),this.store.flushSync()}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}prewarmCaches(){Bs({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds(),skipGitMetadata:!0}).catch(()=>{})}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}noteInventoryChanged(e){if(this.inventoryVersion+=1,this.globalClients.size===0)return;let n={type:"sessions.changed",version:this.inventoryVersion,reason:e},r=JSON.stringify(n);for(let s of this.globalClients)s.readyState===1&&s.send(r)}async createSession(e,n,r,s,i,o,a){s=Vs(s),T.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,ng.stat)(s)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${s}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${s}`);return}if(o)try{let c=(await this.listRecentSessionsForContinue(r,s)).find(u=>!this.isDeletedSession(u.sessionId));if(c)return T.info({sessionId:c.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,c.sessionId,r,s,i);T.info("continue mode: no previous sessions found, creating new")}catch(l){T.warn({error:String(l)},"continue mode: error finding sessions, creating new")}try{let l=this.createDriver(r),c=this.configureDriverBeforeStart(r,l,void 0,a);if(r==="codex"){let g=`pending_${Date.now()}`;T.info({sessionId:g,agent:r,cwd:s},"session created (pending codex startup)"),R.increment("session.create",{agent:r}),k.emit("session.create",{sessionId:g,agent:r,cwd:s,approvalMode:i});let h={sessionId:g,agent:r,cwd:s,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,bufferedPrompts:[],startupToken:1,managed:!0,claudeHookSecret:c,pendingClaudeHookApprovals:new Map};this.sessions.set(g,h),this.registerClaudeHookSession(h),this.store.upsert(Ve(h)),this.updateGauges(),Us(),Gs(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(h,r,"",e),this.reply(e,n,!0,{sessionId:g}),this.startPendingCodexSession(h,e);return}let u=R.startTimer("driver.spawn"),d=await l.start(s,void 0,i),f=u();T.info({sessionId:d,agent:r,spawnMs:f},"session created"),R.increment("session.create",{agent:r}),k.emit("session.create",{sessionId:d,agent:r,cwd:s,approvalMode:i});let p={sessionId:d,agent:r,cwd:s,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:!0,claudeHookSecret:c,pendingClaudeHookApprovals:new Map};this.sessions.set(d,p),this.registerClaudeHookSession(p),this.store.upsert(Ve(p)),this.updateGauges(),Us(),Gs(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(p,r,"",e),this.reply(e,n,!0,{sessionId:d})}catch(l){T.error({agent:r,cwd:s,error:String(l)},"createSession error"),this.reply(e,n,!1,void 0,String(l))}}async resumeSession(e,n,r,s,i,o){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let a=this.sessions.get(r);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated");let f=await gr(r,s,a.cwd),p=this.annotateHistoryMessages(f,a.acceptedClientMessageIds,a.interruptedClientMessageIds),g=this.currentPartialReplyText(a);if(f.length>0||g||a.approvalMode||a.pendingApproval){let h={type:"session.history",sessionId:r,messages:p,...Ks(a.acceptedClientMessageIds),isResponding:a.isResponding||void 0,partialReplyText:g,approvalMode:a.approvalMode,pendingApproval:a.pendingApproval};e.readyState===1&&e.send(JSON.stringify(h))}this.reply(e,n,!0,{sessionId:r});return}let l=this.store.find(r),c=i||l?.cwd||"",u=o??l?.approvalMode,d=l?.title??"Resumed session";try{let f=R.startTimer("driver.spawn"),p=this.createDriver(s),g=this.configureDriverBeforeStart(s,p),h=await p.start(c,r,u),_=f();T.info({sessionId:h,agent:s,spawnMs:_},"session resumed"),R.increment("session.resume",{agent:s}),k.emit("session.resume",{sessionId:h,agent:s,cwd:c});let w={sessionId:h,agent:s,cwd:c,approvalMode:u,driver:p,clients:new Set([e]),title:d,createdAt:l?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:l?.acceptedClientMessageIds??[],interruptedClientMessageIds:l?.interruptedClientMessageIds??[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:l?.managed,pendingApproval:l?.pendingApproval,claudeHookSecret:g,pendingClaudeHookApprovals:new Map};this.sessions.set(h,w),this.registerClaudeHookSession(w),this.store.upsert(Ve(w)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(w,s," (resumed)",e),this.restoreDriverPendingApproval(p,w.pendingApproval);let E=await gr(r,s,c),L=this.annotateHistoryMessages(E,w.acceptedClientMessageIds,w.interruptedClientMessageIds);if(E.length>0||w.pendingApproval){T.info({sessionId:r,historyCount:E.length},"sending history messages");let N={type:"session.history",sessionId:h,messages:L,...Ks(w.acceptedClientMessageIds),approvalMode:u,pendingApproval:w.pendingApproval};e.readyState===1&&e.send(JSON.stringify(N))}this.reply(e,n,!0,{sessionId:h})}catch(f){this.reply(e,n,!1,void 0,String(f))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>wn&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-wn))}rememberInterruptedClientMessage(e,n){e.interruptedClientMessageIds.includes(n)||(e.interruptedClientMessageIds.push(n),e.interruptedClientMessageIds.length>wn&&e.interruptedClientMessageIds.splice(0,e.interruptedClientMessageIds.length-wn))}markLatestAcceptedClientMessageInterrupted(e){let n=e.acceptedClientMessageIds[e.acceptedClientMessageIds.length-1];n&&this.rememberInterruptedClientMessage(e,n)}annotateHistoryMessages(e,n,r){if(!e.length||!n?.length||!r?.length)return e;let s=new Set(r),i=[];for(let u=0;u<e.length;u+=1)e[u]?.role==="user"&&i.push(u);if(i.length===0)return e;let o=Math.min(i.length,n.length);if(o===0)return e;let a=new Map,l=n.length-o,c=i.length-o;for(let u=0;u<o;u+=1){let d=n[l+u];s.has(d)&&a.set(i[c+u],"interrupted")}return a.size===0?e:e.map((u,d)=>u.role==="user"&&a.has(d)?{...u,delivery:"interrupted"}:u)}async sendMessage(e,n,r,s,i,o,a,l){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let c=this.sessions.get(r);if(!c||!c.driver){let f=await this.resolveReconnectSession(r,i,c);if(!f){T.warn({sessionId:r},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}T.info({sessionId:r,agent:f.agent,source:f.source},"auto-reconnecting session"),R.increment("session.reconnect",{agent:f.agent,source:f.source}),k.emit("session.reconnect",{sessionId:r,agent:f.agent,source:f.source});try{let p=this.createDriver(f.agent),g=this.configureDriverBeforeStart(f.agent,p,c?.claudeHookSecret);await p.start(f.cwd,r,f.approvalMode),this.restoreDriverPendingApproval(p,f.pendingApproval),c?(c.approvalMode=f.approvalMode,c.pendingApproval=f.pendingApproval,c.driver=p,c.active=!0,c.clients.add(e),c.lastActivityAt=f.lastActivityAt,c.lastActivityTs=Date.now(),c.isResponding=!1,c.currentReplyText="",c.acceptedClientMessageIds=nt(c.acceptedClientMessageIds,f.acceptedClientMessageIds),c.interruptedClientMessageIds=nt(c.interruptedClientMessageIds,f.interruptedClientMessageIds),c.syntheticApprovalRetries=c.syntheticApprovalRetries??{},c.startupInProgress=!1,c.bufferedPrompts=c.bufferedPrompts??[],c.startupToken=c.startupToken??0,c.claudeHookSecret=g??c.claudeHookSecret,c.pendingClaudeHookApprovals=c.pendingClaudeHookApprovals??new Map):(c={sessionId:r,agent:f.agent,cwd:f.cwd,approvalMode:f.approvalMode,driver:p,clients:new Set([e]),title:f.title,createdAt:f.createdAt,lastActivityAt:f.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:f.acceptedClientMessageIds,interruptedClientMessageIds:f.interruptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:f.managed,pendingApproval:f.pendingApproval,claudeHookSecret:g,pendingClaudeHookApprovals:new Map},this.sessions.set(r,c)),this.registerClaudeHookSession(c),this.bindDriverLifecycle(c,f.agent," (reconnected)"),this.store.upsert(Ve(c)),this.updateGauges(),this.noteInventoryChanged("session_updated")}catch(p){this.reply(e,n,!1,void 0,`Failed to reconnect: ${p}`);return}}if(c.clients.add(e),c.pendingApproval){this.reply(e,n,!1,void 0,"Resolve the pending approval before sending another message.");return}if(o&&this.hasAcceptedClientMessage(c,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(T.info({sessionId:r,clients:c.clients.size,hasDriver:!!c.driver,active:c.active,imageCount:a?.length??0},"sending message"),k.emit("session.send",{sessionId:r,agent:c.agent,messagePreview:s.slice(0,100),imageCount:a?.length??0}),Xp(c),ln(c.title)){let f=ko(s,50);f&&f!==c.title&&(c.title=f),this.store.upsert(Ve(c))}o&&this.rememberAcceptedClientMessage(c,o),this.touchSession(c.sessionId);let u=a?.length?a.map(f=>`[Attached image: ${f}]`).join(`
96
+ `):""}function jm(t){let e=Gm(t?.message?.content);if(/\[Request interrupted by user(?: for tool use)?\]/i.test(e))return!0;let n=t?.toolUseResult;return!!(n&&typeof n=="object"&&n.interrupted===!0||typeof n=="string"&&/\[Request interrupted by user(?: for tool use)?\]/i.test(n))}function vu(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function mr(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,observedApprovalMode:t.approvalMode,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:hi()}}function _r(t,e){let n=(0,M.basename)(e,".jsonl");return t==="claude"?n||null:n.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i)?.[1]??null}async function Vm(t,e){let n=await gu(t,e),r=hu(n,64),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(!s&&typeof u.cwd=="string"&&(s=u.cwd),!i&&typeof u.sessionId=="string"&&(i=u.sessionId),o||(o=Xe([u.customTitle,u.summary])),!l){let d=Sr(u),f=Xe([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||_r("claude",t)||(0,M.basename)(t,".jsonl"),cwd:s,title:o??l??Xe([],a),approvalMode:await mu(t,"claude",e)}:null}async function $m(t,e){let n=await gu(t,e),r=hu(n,96),s="",i="",o,a,l;for(let c of r){let u;try{u=JSON.parse(c)}catch{continue}if(s||(s=u.payload?.cwd??u.cwd??""),i||(i=u.payload?.id??u.id??""),o||(o=Xe([u.payload?.title,u.title])),!l){let d=yu(u),f=d&&!vu(d)?Xe([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||_r("codex",t)||(0,M.basename)(t,".jsonl"),cwd:s,title:o??l??Xe([],a),approvalMode:await mu(t,"codex",e)}:null}async function fn(t,e){let n=await(0,R.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await Vm(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,approvalMode:i.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await $m(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,approvalMode:s.approvalMode,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function lu(t,e){let n=(0,M.join)((0,be.homedir)(),".claude","projects");try{let r;t?r=[pu(t)]:r=(await(0,R.readdir)(n,{withFileTypes:!0})).filter(c=>c.isDirectory()).map(c=>c.name);let s=[];for(let l of r){let c=(0,M.join)(n,l),u=await(0,R.readdir)(c).catch(()=>[]);for(let d of u)d.endsWith(".jsonl")&&s.push((0,M.join)(c,d))}let i=await Ct(s,xt,async l=>{let c=await(0,R.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await Ct(i,xt,async l=>{let c=await fn(l.path,"claude");return c&&e&&e.push(mr(c)),c})).filter(l=>l!==null).map(l=>mr(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Be.warn({error:String(r)},"failed to list claude sessions"),[]}}async function cu(t,e){let n=(0,M.join)((0,be.homedir)(),".codex","sessions");try{let r=await(0,R.readdir)(n).catch(()=>[]),s=[];for(let l of r){let c=(0,M.join)(n,l),u=await(0,R.readdir)(c).catch(()=>[]);for(let d of u){let f=(0,M.join)(c,d),h=await(0,R.readdir)(f).catch(()=>[]);for(let g of h){let p=(0,M.join)(f,g),m=await(0,R.readdir)(p).catch(()=>[]);for(let v of m)v.endsWith(".jsonl")&&s.push((0,M.join)(p,v))}}}let i=await Ct(s,xt,async l=>{let c=await(0,R.stat)(l).catch(()=>null);return{path:l,mtimeMs:c?.mtimeMs??0}});return i.sort((l,c)=>c.mtimeMs-l.mtimeMs),(await Ct(i,xt,async l=>{let c=await fn(l.path,"codex");return c&&e&&(!t||c.cwd===t)&&e.push(mr(c)),c})).filter(l=>l!==null).filter(l=>!t||l.cwd===t).map(l=>mr(l)).sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}catch(r){return Be.warn({error:String(r)},"failed to list codex sessions"),[]}}async function mn(t,e,n){let s=`list:${(0,be.homedir)()}:${t??"all"}:${e??""}`,i=vi.get(s);if(i)return i;let o=gi.get(s);if(o)return o;let a=(async()=>{let l;if(t==="claude")l=await lu(e,n);else if(t==="codex")l=await cu(e,n);else{let[c,u]=await Promise.all([lu(e,n),cu(e,n)]);l=[...c,...u].sort((d,f)=>f.lastActivityAt.localeCompare(d.lastActivityAt))}return vi.set(s,l),l})();return gi.set(s,a),a.finally(()=>gi.delete(s)),a}async function iu(t,e){let r=`search:${(0,be.homedir)()}:${t}:${e??"all"}`,s=Si.get(r);if(s)return s;let i=mi.get(r);if(i)return i;let o=(async()=>{let a=new Set,l=t.toLowerCase();async function c(){let d=(0,M.join)((0,be.homedir)(),".claude","projects");try{let f=await(0,R.readdir)(d,{withFileTypes:!0}),h=[];for(let p of f){if(!p.isDirectory())continue;let m=(0,M.join)(d,p.name),v=await(0,R.readdir)(m).catch(()=>[]);for(let b of v)b.endsWith(".jsonl")&&h.push((0,M.join)(m,b))}let g=await Ct(h,xt,p=>uu(p,l,"claude"));for(let p of g)p&&a.add(p)}catch(f){Be.warn({error:String(f)},"failed to search claude files")}}async function u(){let d=(0,M.join)((0,be.homedir)(),".codex","sessions");try{let f=[];async function h(p){let m=await(0,R.readdir)(p,{withFileTypes:!0}).catch(()=>[]);for(let v of m){let b=(0,M.join)(p,v.name);v.isDirectory()?await h(b):v.name.endsWith(".jsonl")&&f.push(b)}}await h(d);let g=await Ct(f,xt,p=>uu(p,l,"codex"));for(let p of g)p&&a.add(p)}catch(f){Be.warn({error:String(f)},"failed to search codex files")}}return e==="claude"?await c():e==="codex"?await u():await Promise.all([c(),u()]),Si.set(r,a),a})();return mi.set(r,o),o.finally(()=>mi.delete(r)),o}async function uu(t,e,n){let r=(0,bi.createReadStream)(t,{encoding:"utf-8"}),s=(0,wi.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?zm:Ym,o="",a=!1;try{for await(let l of s){if(!l.trim())continue;let c;try{c=JSON.parse(l)}catch{continue}if(o||(n==="claude"?typeof c.sessionId=="string"&&(o=c.sessionId):o=c.payload?.id??c.id??""),!a){let u=i(c);u&&u.toLowerCase().includes(e)&&(a=!0)}if(o&&a)break}}finally{s.close(),r.destroy()}return a?o||_r(n,t):null}function zm(t){return t?.type==="user"&&t.message?.role==="user"?Sr(t):t?.type==="assistant"&&t.message?.role==="assistant"?vr(t.message.content):""}function Ym(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return Ii(t.payload.content)}let e=yu(t);return e||""}async function _i(t,e){let n=(0,bi.createReadStream)(t,{encoding:"utf-8"}),r=(0,wi.createInterface)({input:n,crlfDelay:1/0});try{for await(let s of r){if(!s.trim())continue;let i;try{i=JSON.parse(s)}catch{continue}if(e(i))break}}finally{r.close(),n.destroy()}}async function Su(t,e){let n=(0,M.join)((0,be.homedir)(),".claude","projects"),r=e?pu(e):null,s=await(0,R.readdir)(n).catch(()=>[]),i=r?[r,...s.filter(o=>o!==r)]:s;for(let o of i){let a=(0,M.join)(n,o,`${t}.jsonl`);if((await(0,R.stat)(a).catch(()=>null))?.isFile())return a}return null}async function _u(t,e,n){if(e==="claude")return Su(t,n);let r=(0,M.join)((0,be.homedir)(),".codex","sessions");return wu(r,t)}function Jm(t){if(t?.type==="user"&&t.message?.role==="user")return Wm(t.message.content)?{kind:"toolResult",...jm(t)?{interrupted:!0}:{}}:Sr(t)?{kind:"userPrompt"}:null;if(t?.type==="assistant"&&t.message?.role==="assistant"){let e=vr(t.message.content),n=t.message?.stop_reason;return{kind:"assistant",stopReason:typeof n=="string"?n:n??null,...e?{text:e}:{}}}return t?.type==="system"&&t.subtype==="stop_hook_summary"?{kind:"stopHook"}:null}function Km(t){if(!t)return{};if(t.kind==="stopHook")return{};if(t.kind==="assistant"){let e=t.stopReason==null||t.stopReason==="tool_use";return{...e?{isResponding:!0}:{},...e&&t.text?{partialReplyText:t.text}:{}}}return t.kind==="toolResult"&&t.interrupted?{}:{isResponding:!0}}async function bu(t,e){if(e!=="claude")return{};let n=null;try{await _i(t,r=>{let s=Jm(r);s&&(n=s)})}catch(r){return r.code!=="ENOENT"&&Be.warn({filePath:t,error:String(r)},"failed to read session runtime hints"),{}}return Km(n)}async function Ai(t,e,n){let r=await _u(t,e,n);return r?bu(r,e):{}}async function yn(t,e,n){let r=[],s=(i,o)=>{if(o?.coalesceConsecutiveAssistant&&i.role==="assistant"&&r[r.length-1]?.role==="assistant"){r[r.length-1]=i;return}r.push(i)};if(e==="claude")try{let i=await Su(t,n);i&&await _i(i,o=>{if(o.type==="user"&&o.message?.role==="user"){let a=Sr(o);a&&s({role:"user",content:a})}else if(o.type==="assistant"&&o.message?.role==="assistant"){let a=vr(o.message.content);a&&s({role:"assistant",content:a})}})}catch(i){Be.warn({error:String(i)},"failed to read claude session history")}else if(e==="codex")try{let i=await _u(t,e,n);i&&await _i(i,o=>{if(o.type!=="response_item"||o.payload?.type!=="message")return;let a=o.payload.role;if(a!=="user"&&a!=="assistant")return;let l=Ii(o.payload.content);l&&(a==="user"&&vu(l)||s({role:a,content:l},{coalesceConsecutiveAssistant:!0}))})}catch(i){Be.warn({error:String(i)},"failed to read codex session history")}return r}async function wu(t,e){try{let n=await(0,R.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,M.join)(t,r.name);if(r.isDirectory()){let i=await wu(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){Be.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var Iu=require("child_process");var Au=require("util");var f_=(0,Au.promisify)(Iu.execFile),p_=P.child({module:"process-scanner"});var Qm=null;function br(){Qm=null}var kt=require("fs"),ku=require("path");var Xm=500,Tu=200;function xu(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=Tu?e:e.slice(-Tu)}function Zm(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)typeof n!="string"||n.length===0||e.includes(n)||e.push(n);return e}function ey(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t,n=typeof e.requestId=="string"?e.requestId:"",r=typeof e.toolName=="string"?e.toolName:"",s=typeof e.description=="string"?e.description:"",i=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:{};if(!n||!r||!s)return;let o=e.approvalContext;return o&&typeof o=="object"&&!Array.isArray(o)&&o.provider==="codex"&&typeof o.kind=="string"&&typeof o.rpcId=="number"?{requestId:n,toolName:r,input:i,description:s,approvalContext:{provider:"codex",kind:o.kind,rpcId:o.rpcId,...typeof o.questionId=="string"?{questionId:o.questionId}:{},...typeof o.approveLabel=="string"?{approveLabel:o.approveLabel}:{},...typeof o.denyLabel=="string"?{denyLabel:o.denyLabel}:{}}}:{requestId:n,toolName:r,input:i,description:s}}function Cu(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:xu(t.acceptedClientMessageIds),interruptedClientMessageIds:xu(t.interruptedClientMessageIds),pendingApproval:ey(t.pendingApproval)}}function ty(t){if(Array.isArray(t))return{records:t.map(Cu),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(Cu):[],deletedSessionIds:Zm(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var wr=class{records;deletedSessionIds;debounceTimer=null;constructor(){let e=this.loadFromDisk();this.records=e.records,this.deletedSessionIds=new Set(e.deletedSessionIds)}getAll(){return this.records}getDeletedSessionIds(){return[...this.deletedSessionIds]}find(e){return this.records.find(n=>n.sessionId===e)}isDeleted(e){return this.deletedSessionIds.has(e)}upsert(e){this.deletedSessionIds.delete(e.sessionId);let n=this.records.findIndex(r=>r.sessionId===e.sessionId);n>=0?this.records[n]=e:this.records.unshift(e),this.scheduleSave()}remove(e){this.records=this.records.filter(n=>n.sessionId!==e),this.deletedSessionIds.add(e),this.scheduleSave()}flushSync(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.saveToDisk()}scheduleSave(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.saveToDisk()},Xm)}loadFromDisk(){try{let e=(0,kt.readFileSync)(er,"utf-8");return ty(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,kt.mkdirSync)((0,ku.dirname)(er),{recursive:!0}),(0,kt.writeFileSync)(er,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var Et=require("path"),Eu=require("os");function Ir(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,Et.join)((0,Eu.homedir)(),t.slice(2)):t}function ny(t){let e=t.trim();if(!e)return"";let n=e.indexOf("#");n>0&&(e=e.slice(0,n));let r=e.match(/^(.*?)(:\d+(?::\d+)?)$/);return r&&(e=r[1]??e),e}function Ti(t,e){let n=Ir(ny(t));if(!n||(0,Et.isAbsolute)(n))return n;let r=Ir(e??"");return r?(0,Et.resolve)(r,n):n}var Pu={approvalRequestV1:"vibelet.approvalRequest.v1"};var Pt=require("fs"),Ru=require("path");function ry(t){return!!(t&&typeof t=="object"&&typeof t.deviceId=="string"&&typeof t.pushToken=="string"&&t.platform==="expo"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string"&&(typeof t.lastSentAt=="string"||typeof t.lastSentAt>"u"))}function sy(t){try{let e=(0,Pt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(ry):[]}catch{return[]}}function vn(t,e){(0,Pt.mkdirSync)((0,Ru.dirname)(t),{recursive:!0}),(0,Pt.writeFileSync)(t,JSON.stringify(e,null,2)+`
97
+ `,"utf8")}var Ar=class{constructor(e=sc){this.pushSubscriptionsPath=e;this.records=sy(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}count(){return this.records.length}register(e,n){let r=new Date().toISOString(),s=this.records.find(o=>o.deviceId===e),i={deviceId:e,pushToken:n,platform:"expo",createdAt:s?.createdAt??r,updatedAt:r,...s?.lastSentAt?{lastSentAt:s.lastSentAt}:{}};this.records=[i,...this.records.filter(o=>o.deviceId!==e&&o.pushToken!==n)],vn(this.pushSubscriptionsPath,this.records)}unregister(e,n){let r=this.records.filter(s=>!(s.deviceId===e&&s.pushToken===n));return r.length===this.records.length?!1:(this.records=r,vn(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let n=this.records.filter(r=>r.pushToken!==e);return n.length===this.records.length?!1:(this.records=n,vn(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let n=new Set(e),r=new Date().toISOString(),s=!1;for(let i of this.records)n.has(i.pushToken)&&(i.lastSentAt=r,s=!0);s&&vn(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],vn(this.pushSubscriptionsPath,this.records)}};var z=P.child({module:"push"}),iy="https://exp.host/--/api/v2/push/send",oy="https://exp.host/--/api/v2/push/getReceipts",ay=[0,1e3,3e3],Sn=new Ar;function ly(t){return!!(t&&typeof t=="object"&&typeof t.daemonId=="string"&&typeof t.canonicalHost=="string"&&typeof t.sessionId=="string"&&(t.agent==="claude"||t.agent==="codex")&&(t.eventType==="reply_ready"||t.eventType==="approval_request")&&(typeof t.requestId>"u"||typeof t.requestId=="string"))}function cy(t){return new Promise(e=>{setTimeout(e,t)})}function Mu(t){return t==="DeviceNotRegistered"}function uy(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let n=[],r=[];for(let[s,i]of t.data.entries()){let o=e[s];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){n.push(o);continue}r.push({token:o,ticket:i})}}return{successfulTokens:n,ticketErrors:r}}function dy(t,e){let n=new Map;if(!Array.isArray(t.data))return n;for(let[r,s]of t.data.entries()){let i=e[r];!i||!s||s.status!=="ok"||typeof s.id!="string"||s.id.length===0||n.set(s.id,i)}return n}function fy(t,e){let n=[],r=[],s=t.data;for(let[i,o]of e.entries()){let a=s?.[i];if(!a||typeof a!="object"){n.push(i);continue}a.status==="error"&&r.push({token:o,receipt:a})}return{pendingTicketIds:n,receiptErrors:r}}async function py(t,e,n,r){let s=new Map(t);for(let i of ay){if(s.size===0)return;i>0&&await n(i);let o;try{o=await e(oy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...s.keys()]})})}catch(u){z.error({error:String(u),count:s.size},"push receipt request failed");return}if(!o.ok){z.error({status:o.status,statusText:o.statusText,count:s.size},"push receipt request returned error status");return}let a=await o.json().catch(()=>null);if(!a){z.error({count:s.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:c}=fy(a,s);for(let{token:u,receipt:d}of c){let f=d.details?.error;if(z.error({token:u,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),Mu(f)){let h=r.unregisterToken(u);z.info({token:u,errorCode:f,removed:h},"push token removed after receipt rejection")}}s=new Map(l.map(u=>[u,s.get(u)]))}s.size>0&&z.warn({pendingReceipts:s.size},"push receipts still pending after polling")}function hy(t){let e=t?.pushStore??Sn,n=t?.fetchImpl??globalThis.fetch,r=t?.sleepImpl??cy;return async function(i,o,a){let l=e.listTokens();if(l.length===0)return;let c=l.map(u=>({to:u,sound:"default",title:i,body:o,data:a,badge:1,...ly(a)&&a.eventType==="approval_request"?{categoryId:Pu.approvalRequestV1}:{}}));try{let u=await n(iy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok){z.error({status:u.status,statusText:u.statusText},"push send failed");return}let d=await u.json().catch(()=>null);if(!d){z.error({count:c.length},"push send returned unreadable response");return}let{successfulTokens:f,ticketErrors:h}=uy(d,l),g=dy(d,l);for(let{token:p,ticket:m}of h){let v=m.details?.error;if(z.error({token:p,message:m.message,details:m.details,ticketStatus:m.status},"push ticket rejected"),Mu(v)){let b=e.unregisterToken(p);z.info({token:p,errorCode:v,removed:b},"push token removed after ticket rejection")}}f.length>0&&(z.debug({count:f.length},"push sent"),e.markSent(f)),g.size>0&&await py(g,n,r,e)}catch(u){z.error({error:String(u)},"push send error")}}}function xi(t,e){Sn.register(t,e),z.info({deviceId:t,token:e,total:Sn.count()},"push token registered")}function Ci(t,e){let n=Sn.unregister(t,e);z.info({deviceId:t,token:e,total:Sn.count(),removed:n},"push token unregistered")}var Tr=hy();var _=P.child({module:"manager"}),gy="Done.",my="Approval required",Lu=180,Rt=200;function we(...t){let e=[];for(let n of t)if(n?.length)for(let r of n)!r||e.includes(r)||(e.push(r),e.length>Rt&&e.splice(0,e.length-Rt));return e}function xr(t){return t?.length?{acceptedClientMessageIds:we(t)}:{}}function he(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:we(t.acceptedClientMessageIds),interruptedClientMessageIds:we(t.interruptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,managed:t.managed,isResponding:t.isResponding||void 0}}function Nu(t){t.managed||(t.managed=!0)}function Ou(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&lr(e)}function Bu(t,e,n){return{sessionId:t,agent:e,...n}}function yy(t){return t.startsWith(ei)}function Du(t){return t?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}:{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Denied from Vibelet"}}}var Cr=class{constructor(e=Tr){this.pushSender=e;this.removeInventoryBackfillListener=eu(()=>{this.noteInventoryChanged("inventory_backfilled")}),this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new wr;idleSweepInterval=null;globalClients=new Set;inventoryVersion=0;removeInventoryBackfillListener;startIdleSweep(){S.idleTimeoutMs<=0&&S.turnStallTimeoutMs<=0||(this.idleSweepInterval=setInterval(()=>this.sweepIdleSessions(),6e4),this.idleSweepInterval.unref())}stopIdleSweep(){this.idleSweepInterval&&(clearInterval(this.idleSweepInterval),this.idleSweepInterval=null)}sweepIdleSessions(){let e=Date.now(),n=S.idleTimeoutMs,r=S.turnStallTimeoutMs;if(n<=0&&r<=0)return;let s=3600*1e3;for(let[i,o]of this.sessions){if(!o.active&&!o.driver){if(o.clients.size===0){let l=e-o.lastActivityTs;l>=s&&(_.info({sessionId:o.sessionId,inactiveMs:l},"removing inactive session from memory"),w.increment("session.cleanup",{reason:"inactive"}),this.unregisterClaudeHookSession(o),this.sessions.delete(i))}continue}if(!o.active||!o.driver)continue;let a=e-o.lastActivityTs;if(o.isResponding){if(r<=0||o.pendingApproval||a<r)continue;_.warn({sessionId:o.sessionId,agent:o.agent,inactiveMs:a,turnStallTimeoutMs:r},"stopping stalled driver"),w.increment("driver.stall_timeout",{agent:o.agent}),I.emit("driver.stall_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),this.resolvePendingClaudeHookApprovals(o),o.driver.stop(),o.active=!1,o.driver=null,o.isResponding=!1,o.currentReplyText="",this.updateGauges(),this.broadcast(o.sessionId,{type:"error",sessionId:o.sessionId,message:`Agent stopped responding for over ${Math.ceil(r/1e3)}s. Send a new message to continue.`}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated");continue}o.pendingApproval||n<=0||a<n||(_.info({sessionId:o.sessionId,agent:o.agent,idleMs:a,timeoutMs:n},"stopping idle driver"),w.increment("driver.idle_timeout",{agent:o.agent}),I.emit("driver.idle_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),o.driver.stop(),o.active=!1,o.driver=null,this.updateGauges(),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"))}}bindDriverLifecycle(e,n,r,s){let i=e.driver;i?.onMessage(o=>{if(e.driver!==i){_.info({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"ignoring stale driver message");return}if(_.debug({agent:n,context:r,msgType:o.type,sessionId:e.sessionId},"driver message received"),o.type!=="response"&&"sessionId"in o&&o.sessionId&&o.sessionId!==e.sessionId&&!this.sessions.has(o.sessionId)&&this.remapSessionId(e,o.sessionId,s),(o.type==="session.done"||o.type==="session.interrupted")&&(e.isResponding=!1,o.type==="session.interrupted"&&this.markLatestAcceptedClientMessageInterrupted(e),(o.type==="session.interrupted"||!Ou(e))&&(e.pendingApproval=void 0)),o.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(o.requestId,!0)??!1){I.emit("approval.response",{sessionId:e.sessionId,requestId:o.requestId,approved:!0}),e.pendingApproval=void 0,e.isResponding=!0,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated");return}_.warn({sessionId:e.sessionId,requestId:o.requestId},"failed to auto-approve codex request; falling back to pending approval flow")}e.isResponding=!1,e.pendingApproval={requestId:o.requestId,toolName:o.toolName,input:o.input,description:o.description,...o.approvalContext?{approvalContext:o.approvalContext}:{}},this.pushSender(my,this.buildPushBody(`${e.title||e.sessionId}: ${o.description||o.toolName}`),{sessionId:e.sessionId,agent:e.agent,requestId:o.requestId,eventType:"approval_request"})}n==="claude"&&o.type==="approval.request"&&lr(o.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[o.requestId]={message:e.lastUserMessage,toolName:o.toolName}:_.warn({sessionId:e.sessionId,requestId:o.requestId},"missing lastUserMessage for synthetic approval retry")),this.touchSession(e.sessionId,o.type!=="text.delta"),(o.type==="approval.request"||o.type==="session.done"||o.type==="session.interrupted")&&this.noteInventoryChanged("session_updated"),this.broadcast(e.sessionId,o),(o.type==="session.done"||o.type==="session.interrupted")&&e.bufferedPrompts.length>0&&this.flushBufferedPrompt(e)}),i?.onExit?.(o=>{if(e.driver!==i){_.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"ignoring stale driver exit");return}_.info({agent:n,context:r,exitCode:o,sessionId:e.sessionId},"driver exited"),I.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:o}),w.increment("driver.exit",{agent:n,abnormal:o&&o!==0?"true":"false"});let a=!!(e.pendingApproval&&(e.agent==="codex"||o===0&&Ou(e)));this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",a||(e.pendingApproval=void 0),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated")})}remapSessionId(e,n,r){if(!n||n===e.sessionId)return;let s=this.sessions.get(n);if(s&&s!==e){_.warn({oldSessionId:e.sessionId,newSessionId:n},"skipping session ID remap because target already exists");return}let i=e.sessionId;_.info({oldSessionId:i,newSessionId:n},"session ID updated"),this.store.remove(i),this.sessions.delete(i),e.sessionId=n,this.sessions.set(n,e),this.store.upsert(he(e)),this.noteInventoryChanged("session_remapped"),r&&this.reply(r,`id_update_${Date.now()}`,!0,{sessionId:n,oldSessionId:i})}flushBufferedPrompt(e,n=!1){if(!e.driver||!e.active||e.startupInProgress||e.pendingApproval||!n&&e.isResponding)return!1;let r=e.bufferedPrompts.shift();return r?(e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=r,this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),e.driver.sendPrompt(r,e.model),!0):!1}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let r=e.driver,s=e.sessionId,i=e.startupToken,o=w.startTimer("driver.spawn");(async()=>{try{let a=await r.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(s)!==e||e.startupToken!==i||e.driver!==r){_.info({pendingSessionId:s,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,_.info({pendingSessionId:s,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==s&&this.remapSessionId(e,a,n),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(s)!==e||e.startupToken!==i){_.info({pendingSessionId:s,error:String(a)},"ignoring stale codex startup failure");return}e.startupInProgress=!1,e.bufferedPrompts=[],e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),_.error({sessionId:s,cwd:e.cwd,error:String(a)},"async codex createSession error"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to start Codex session: ${String(a)}`})}})()}configureDriverBeforeStart(e,n,r,s){if(e==="codex"&&n instanceof cn&&s&&n.setModel(s),e!=="claude"||!(n instanceof ln))return;let i=r??(0,ki.randomUUID)().replace(/-/g,"");return n.configureHookBridge(S.port,i),i}registerClaudeHookSession(e){e.agent!=="claude"||!e.claudeHookSecret||this.claudeHookSessions.set(e.claudeHookSecret,e)}unregisterClaudeHookSession(e){if(e.agent!=="claude"||!e.claudeHookSecret)return;this.claudeHookSessions.get(e.claudeHookSecret)===e&&this.claudeHookSessions.delete(e.claudeHookSecret)}resolvePendingClaudeHookApprovals(e,n=an){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&yy(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let n=e.trim();if(n)return this.claudeHookSessions.get(n)}handleClaudeSessionStartHook(e,n){let r=this.resolveClaudeHookSession(e);return r?(this.touchSession(r.sessionId),!0):(_.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,n){let r=this.resolveClaudeHookSession(e);if(!r||r.agent!=="claude"||!r.active)return _.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),an;if(r.approvalMode==="autoApprove")return Du(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return an;let o=n.tool_input??n.toolInput,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},l=typeof n.tool_use_id=="string"?n.tool_use_id:typeof n.toolUseId=="string"?n.toolUseId:"",c=`${ei}${l.trim()||(0,ki.randomUUID)()}`,u=r.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${i}.`,f,h=new Promise(g=>{f=g});return r.pendingClaudeHookApprovals.set(c,{requestId:c,promise:h,resolve:g=>{r.pendingClaudeHookApprovals.delete(c),f(g)}}),r.pendingApproval={requestId:c,toolName:i,input:a,description:d},I.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:i}),this.touchSession(r.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(r.sessionId,{type:"approval.request",sessionId:r.sessionId,requestId:c,toolName:i,input:a,description:d}),h}async resolveReconnectSession(e,n,r){if(this.isDeletedSession(e))return;let s=new Date().toISOString(),i=r?.agent,o=r?.cwd??"",a=r?.approvalMode,l=r?.pendingApproval,c=r?.title??"",u=r?.createdAt??s,d=r?.lastActivityAt??s,f=we(r?.acceptedClientMessageIds),h=we(r?.interruptedClientMessageIds),g=r?.isResponding,p=r?"memory":"client",m=this.store.find(e);if(m)i=m.agent,o=m.cwd||o,a=m.approvalMode??a,l=m.pendingApproval??l,c=m.title||c,u=m.createdAt||u,d=m.lastActivityAt||d,f=we(m.acceptedClientMessageIds,f),h=we(m.interruptedClientMessageIds,h),p="record";else if(!r){let b=(await mn(n??i)).find(K=>K.sessionId===e);b&&(i=b.agent,o=b.cwd||o,c=b.title??c,u=b.createdAt,d=b.lastActivityAt,g=b.runtime.isResponding??g,p="scanner")}if(!i&&n&&(i=n,p=r?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,pendingApproval:l,title:c,createdAt:u,lastActivityAt:d,acceptedClientMessageIds:f,interruptedClientMessageIds:h,source:p,managed:r?.managed??m?.managed,isResponding:g||void 0}}collectReconnectPendingApprovals(){let e=[],n=new Set;for(let r of this.sessions.values()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(Bu(r.sessionId,r.agent,r.pendingApproval)))}for(let r of this.store.getAll()){if(!r.pendingApproval)continue;let s=`${r.agent}:${r.sessionId}:${r.pendingApproval.requestId}`;n.has(s)||(n.add(s),e.push(Bu(r.sessionId,r.agent,r.pendingApproval)))}return e}restoreDriverPendingApproval(e,n){n&&e.restorePendingApproval?.(n)}async reviveSessionForApproval(e){if(e.driver)return!0;if(!e.pendingApproval||e.agent!=="codex")return!1;let n=this.createDriver(e.agent),r=this.configureDriverBeforeStart(e.agent,n,e.claudeHookSecret);return await n.start(e.cwd,e.sessionId,e.approvalMode),this.restoreDriverPendingApproval(n,e.pendingApproval),e.driver=n,e.active=!0,e.isResponding=!1,e.currentReplyText="",e.startupInProgress=!1,e.bufferedPrompts=e.bufferedPrompts??[],e.startupToken=e.startupToken??0,e.claudeHookSecret=r??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval resumed)"),this.store.upsert(he(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),!0}buildPushBody(e){let n=e.replace(/\s+/g," ").trim();return n?n.length<=Lu?n:`${n.slice(0,Math.max(1,Lu-3)).trimEnd()}...`:gy}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}touchSession(e,n=!0){let r=new Date().toISOString(),s=this.sessions.get(e);if(s){s.lastActivityAt=r,s.lastActivityTs=Date.now(),n&&this.store.upsert(he(s));return}let i=this.store.find(e);i&&this.store.upsert({...i,lastActivityAt:r})}updateGauges(){let e=0;for(let n of this.sessions.values())n.active&&e++;w.gauge("session.active",e)}activeSessionSnapshots(){let e=[];for(let n of this.sessions.values())n.sessionId.startsWith("pending_")||n.active&&e.push({sessionId:n.sessionId,agent:n.agent,cwd:n.cwd,approvalMode:n.approvalMode,title:n.title,createdAt:n.createdAt,lastActivityAt:n.lastActivityAt,...n.pendingApproval?{needsAttention:!0}:{},...n.isResponding?{isResponding:!0}:{},managed:n.managed});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,n){return mn(e,n)}async handle(e,n){switch(_.debug({action:n.action},"handling client message"),n.action){case"session.create":await this.createSession(e,n.id,n.agent,n.cwd,n.approvalMode,n.continueSession,n.model);break;case"session.resume":await this.resumeSession(e,n.id,n.sessionId,n.agent);break;case"session.send":await this.sendMessage(e,n.id,n.sessionId,n.message,n.agent,n.clientMessageId,n.images,n.model);break;case"session.approve":await this.approve(e,n.id,n.sessionId,n.requestId,n.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,n.id,n.sessionId,n.approvalMode);break;case"session.interrupt":this.interrupt(e,n.id,n.sessionId);break;case"session.stop":this.stopSession(e,n.id,n.sessionId);break;case"session.delete":this.deleteSession(e,n.id,n.sessionId);break;case"session.history":await this.sendHistory(e,n.id,n.sessionId,n.agent);break;case"reconnect.snapshot":await this.sendReconnectSnapshot(e,n.id,n.agent,n.cwd,n.search,n.activeSessionId,n.activeAgent,n.customTitles);break;case"sessions.list":await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor,n.customTitles);break}}addGlobalClient(e){this.globalClients.add(e)}removeClient(e){this.globalClients.delete(e);for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep(),this.removeInventoryBackfillListener(),this.globalClients.clear();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),e.driver?.stop()}catch(n){_.error({sessionId:e.sessionId,agent:e.agent,error:String(n)},"failed to stop session on shutdown")}e.active=!1,e.driver=null,e.clients.clear(),this.unregisterClaudeHookSession(e)}this.claudeHookSessions.clear(),this.store.flushSync()}getActiveSessionCount(){let e=0;for(let n of this.sessions.values())n.active&&e++;return e}prewarmCaches(){gr({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds(),skipGitMetadata:!0}).catch(()=>{})}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}noteInventoryChanged(e){if(this.inventoryVersion+=1,this.globalClients.size===0)return;let n={type:"sessions.changed",version:this.inventoryVersion,reason:e},r=JSON.stringify(n);for(let s of this.globalClients)s.readyState===1&&s.send(r)}async createSession(e,n,r,s,i,o,a){s=Ir(s),_.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,Hu.stat)(s)).isDirectory()){this.reply(e,n,!1,void 0,`Path is not a directory: ${s}`);return}}catch{this.reply(e,n,!1,void 0,`Directory does not exist: ${s}`);return}if(o)try{let c=(await this.listRecentSessionsForContinue(r,s)).find(u=>!this.isDeletedSession(u.sessionId));if(c)return _.info({sessionId:c.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,c.sessionId,r,s,i);_.info("continue mode: no previous sessions found, creating new")}catch(l){_.warn({error:String(l)},"continue mode: error finding sessions, creating new")}try{let l=this.createDriver(r),c=this.configureDriverBeforeStart(r,l,void 0,a);if(r==="codex"){let g=`pending_${Date.now()}`;_.info({sessionId:g,agent:r,cwd:s},"session created (pending codex startup)"),w.increment("session.create",{agent:r}),I.emit("session.create",{sessionId:g,agent:r,cwd:s,approvalMode:i});let p={sessionId:g,agent:r,cwd:s,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,bufferedPrompts:[],startupToken:1,managed:!0,claudeHookSecret:c,pendingClaudeHookApprovals:new Map};this.sessions.set(g,p),this.registerClaudeHookSession(p),this.store.upsert(he(p)),this.updateGauges(),yr(),br(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(p,r,"",e),this.reply(e,n,!0,{sessionId:g}),this.startPendingCodexSession(p,e);return}let u=w.startTimer("driver.spawn"),d=await l.start(s,void 0,i),f=u();_.info({sessionId:d,agent:r,spawnMs:f},"session created"),w.increment("session.create",{agent:r}),I.emit("session.create",{sessionId:d,agent:r,cwd:s,approvalMode:i});let h={sessionId:d,agent:r,cwd:s,approvalMode:i,model:a,driver:l,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],interruptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:!0,claudeHookSecret:c,pendingClaudeHookApprovals:new Map};this.sessions.set(d,h),this.registerClaudeHookSession(h),this.store.upsert(he(h)),this.updateGauges(),yr(),br(),this.noteInventoryChanged("session_created"),this.bindDriverLifecycle(h,r,"",e),this.reply(e,n,!0,{sessionId:d})}catch(l){_.error({agent:r,cwd:s,error:String(l)},"createSession error"),this.reply(e,n,!1,void 0,String(l))}}async resumeSession(e,n,r,s,i,o){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let a=this.sessions.get(r);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId),this.noteInventoryChanged("session_updated");let f=await yn(r,s,a.cwd),h=this.annotateHistoryMessages(f,a.acceptedClientMessageIds,a.interruptedClientMessageIds),g=this.currentPartialReplyText(a);if(f.length>0||g||a.approvalMode||a.pendingApproval){let p={type:"session.history",sessionId:r,messages:h,...xr(a.acceptedClientMessageIds),isResponding:a.isResponding||void 0,partialReplyText:g,approvalMode:a.approvalMode,pendingApproval:a.pendingApproval};e.readyState===1&&e.send(JSON.stringify(p))}this.reply(e,n,!0,{sessionId:r});return}let l=this.store.find(r),c=i||l?.cwd||"",u=o??l?.approvalMode,d=l?.title??"Resumed session";try{let f=w.startTimer("driver.spawn"),h=this.createDriver(s),g=this.configureDriverBeforeStart(s,h),p=await h.start(c,r,u),m=f();_.info({sessionId:p,agent:s,spawnMs:m},"session resumed"),w.increment("session.resume",{agent:s}),I.emit("session.resume",{sessionId:p,agent:s,cwd:c});let v={sessionId:p,agent:s,cwd:c,approvalMode:u,driver:h,clients:new Set([e]),title:d,createdAt:l?.createdAt??new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:l?.acceptedClientMessageIds??[],interruptedClientMessageIds:l?.interruptedClientMessageIds??[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:l?.managed,pendingApproval:l?.pendingApproval,claudeHookSecret:g,pendingClaudeHookApprovals:new Map};this.sessions.set(p,v),this.registerClaudeHookSession(v),this.store.upsert(he(v)),this.updateGauges(),this.noteInventoryChanged("session_updated"),this.bindDriverLifecycle(v,s," (resumed)",e),this.restoreDriverPendingApproval(h,v.pendingApproval);let b=await yn(r,s,c),K=this.annotateHistoryMessages(b,v.acceptedClientMessageIds,v.interruptedClientMessageIds);if(b.length>0||v.pendingApproval){_.info({sessionId:r,historyCount:b.length},"sending history messages");let C={type:"session.history",sessionId:p,messages:K,...xr(v.acceptedClientMessageIds),approvalMode:u,pendingApproval:v.pendingApproval};e.readyState===1&&e.send(JSON.stringify(C))}this.reply(e,n,!0,{sessionId:p})}catch(f){this.reply(e,n,!1,void 0,String(f))}}hasAcceptedClientMessage(e,n){return e.acceptedClientMessageIds.includes(n)}rememberAcceptedClientMessage(e,n){this.hasAcceptedClientMessage(e,n)||(e.acceptedClientMessageIds.push(n),e.acceptedClientMessageIds.length>Rt&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-Rt))}rememberInterruptedClientMessage(e,n){e.interruptedClientMessageIds.includes(n)||(e.interruptedClientMessageIds.push(n),e.interruptedClientMessageIds.length>Rt&&e.interruptedClientMessageIds.splice(0,e.interruptedClientMessageIds.length-Rt))}markLatestAcceptedClientMessageInterrupted(e){let n=e.acceptedClientMessageIds[e.acceptedClientMessageIds.length-1];n&&this.rememberInterruptedClientMessage(e,n)}annotateHistoryMessages(e,n,r){if(!e.length||!n?.length||!r?.length)return e;let s=new Set(r),i=[];for(let u=0;u<e.length;u+=1)e[u]?.role==="user"&&i.push(u);if(i.length===0)return e;let o=Math.min(i.length,n.length);if(o===0)return e;let a=new Map,l=n.length-o,c=i.length-o;for(let u=0;u<o;u+=1){let d=n[l+u];s.has(d)&&a.set(i[c+u],"interrupted")}return a.size===0?e:e.map((u,d)=>u.role==="user"&&a.has(d)?{...u,delivery:"interrupted"}:u)}async sendMessage(e,n,r,s,i,o,a,l){if(this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}let c=this.sessions.get(r);if(!c||!c.driver){let f=await this.resolveReconnectSession(r,i,c);if(!f){_.warn({sessionId:r},"session not found in records or scanner"),this.reply(e,n,!1,void 0,"Session not found");return}_.info({sessionId:r,agent:f.agent,source:f.source},"auto-reconnecting session"),w.increment("session.reconnect",{agent:f.agent,source:f.source}),I.emit("session.reconnect",{sessionId:r,agent:f.agent,source:f.source});try{let h=this.createDriver(f.agent),g=this.configureDriverBeforeStart(f.agent,h,c?.claudeHookSecret);await h.start(f.cwd,r,f.approvalMode),this.restoreDriverPendingApproval(h,f.pendingApproval),c?(c.approvalMode=f.approvalMode,c.pendingApproval=f.pendingApproval,c.driver=h,c.active=!0,c.clients.add(e),c.lastActivityAt=f.lastActivityAt,c.lastActivityTs=Date.now(),c.isResponding=!1,c.currentReplyText="",c.acceptedClientMessageIds=we(c.acceptedClientMessageIds,f.acceptedClientMessageIds),c.interruptedClientMessageIds=we(c.interruptedClientMessageIds,f.interruptedClientMessageIds),c.syntheticApprovalRetries=c.syntheticApprovalRetries??{},c.startupInProgress=!1,c.bufferedPrompts=c.bufferedPrompts??[],c.startupToken=c.startupToken??0,c.claudeHookSecret=g??c.claudeHookSecret,c.pendingClaudeHookApprovals=c.pendingClaudeHookApprovals??new Map):(c={sessionId:r,agent:f.agent,cwd:f.cwd,approvalMode:f.approvalMode,driver:h,clients:new Set([e]),title:f.title,createdAt:f.createdAt,lastActivityAt:f.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:f.acceptedClientMessageIds,interruptedClientMessageIds:f.interruptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:f.managed,pendingApproval:f.pendingApproval,claudeHookSecret:g,pendingClaudeHookApprovals:new Map},this.sessions.set(r,c)),this.registerClaudeHookSession(c),this.bindDriverLifecycle(c,f.agent," (reconnected)"),this.store.upsert(he(c)),this.updateGauges(),this.noteInventoryChanged("session_updated")}catch(h){this.reply(e,n,!1,void 0,`Failed to reconnect: ${h}`);return}}if(c.clients.add(e),c.pendingApproval){this.reply(e,n,!1,void 0,"Resolve the pending approval before sending another message.");return}if(o&&this.hasAcceptedClientMessage(c,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(_.info({sessionId:r,clients:c.clients.size,hasDriver:!!c.driver,active:c.active,imageCount:a?.length??0},"sending message"),I.emit("session.send",{sessionId:r,agent:c.agent,messagePreview:s.slice(0,100),imageCount:a?.length??0}),Nu(c),It(c.title)){let f=oi(s,50);f&&f!==c.title&&(c.title=f),this.store.upsert(he(c))}o&&this.rememberAcceptedClientMessage(c,o),this.touchSession(c.sessionId);let u=a?.length?a.map(f=>`[Attached image: ${f}]`).join(`
99
98
  `):"",d=u?s?`${s}
100
99
 
101
- ${u}`:u:s;if(l!==void 0&&(c.model=l||void 0),c.startupInProgress){c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,c.bufferedPrompts.push(d),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}if(c.isResponding){c.bufferedPrompts.push(d),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,this.noteInventoryChanged("session_updated"),c.driver.sendPrompt(d,c.model),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0)}async sendReconnectSnapshot(e,n,r,s,i,o,a,l){try{let c=this.getDeletedSessionIds(),u;try{u=await Bs({agent:r,cwd:s,search:i,customTitles:l,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:c})}catch(p){T.warn({error:String(p)},"failed to build reconnect snapshot session list"),u={sessions:[],nextCursor:void 0}}u={...u,inventoryVersion:this.inventoryVersion};let d;if(o&&!c.has(o)){let p=a??u.sessions.find(_=>_.sessionId===o)?.agent,g=this.sessions.get(o);g&&g.clients.add(e);let h=await this.resolveReconnectSession(o,p,g);if(h){let _=await gr(o,h.agent,g?.cwd??h.cwd),w=this.annotateHistoryMessages(_,g?.acceptedClientMessageIds??h.acceptedClientMessageIds,g?.interruptedClientMessageIds??h.interruptedClientMessageIds),E=g?{}:await ja(o,h.agent,h.cwd);d={sessionId:o,agent:h.agent,messages:w,...Ks(g?.acceptedClientMessageIds??h.acceptedClientMessageIds),isResponding:g?.isResponding??E.isResponding??h.isResponding,partialReplyText:g?this.currentPartialReplyText(g):E.partialReplyText,approvalMode:g?.approvalMode??h.approvalMode,...g?.pendingApproval?{pendingApproval:g.pendingApproval}:{}}}}let f=this.collectReconnectPendingApprovals();R.increment("reconnect.snapshot",{activeSession:d?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:u.sessions,nextCursor:u.nextCursor,inventoryVersion:u.inventoryVersion,...d?{activeSession:d}:{},...f.length>0?{pendingApprovals:f}:{}}})}catch(c){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(c)}`)}}async approve(e,n,r,s,i){let o=this.sessions.get(r),a=o?.pendingApproval,l=o?.pendingClaudeHookApprovals.get(s);if(o&&l){o.pendingApproval=void 0,k.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),l.resolve(tg(i)),o.isResponding=!0,this.reply(e,n,!0);return}let c=o?.syntheticApprovalRetries[s];if(o&&c&&us(s)){delete o.syntheticApprovalRetries[s],o.pendingApproval=void 0,k.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0),i&&await this.retrySyntheticClaudeApproval(o,c);return}if(o&&!o.driver&&a)try{await this.reviveSessionForApproval(o)}catch(d){this.reply(e,n,!1,void 0,`Failed to restore approval session: ${String(d)}`);return}if(!o?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(k.emit("approval.response",{sessionId:r,requestId:s,approved:i}),!o.driver.respondApproval(s,i)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}o.pendingApproval=void 0,this.touchSession(o.sessionId),o.isResponding=!0,this.noteInventoryChanged("session_updated"),this.reply(e,n,!0)}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let r=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",s=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,s,e.claudeHookSecret);await s.start(e.cwd,e.sessionId,r),e.driver=s,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken=0,e.claudeHookSecret=i??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(Ve(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),T.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),s.sendPrompt(n.message,e.model)}catch(r){e.driver=null,e.active=!1,e.isResponding=!1,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken+=1,this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),T.error({sessionId:e.sessionId,error:String(r)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(r)}`})}}async setApprovalMode(e,n,r,s){let i=this.sessions.get(r);if(!i){let a=this.store.find(r);a?(s===null?delete a.approvalMode:a.approvalMode=s,this.store.upsert(a),this.noteInventoryChanged("session_updated"),T.info({sessionId:r,agent:a.agent,newMode:s},"approval mode changed (inactive session)")):T.info({sessionId:r,newMode:s},"approval mode changed (untracked session)"),this.reply(e,n,!0,{approvalMode:s});return}if(s===null){this.reply(e,n,!1,void 0,"Follow Remote is only available for external sessions");return}let o=i.approvalMode;i.approvalMode=s,this.store.upsert(Ve(i)),this.noteInventoryChanged("session_updated"),T.info({sessionId:r,agent:i.agent,oldMode:o,newMode:s},"approval mode changed"),i.driver&&i.driver.setApprovalMode(s),this.reply(e,n,!0,{approvalMode:s})}interrupt(e,n,r){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(k.emit("session.interrupt",{sessionId:r,agent:s.agent}),!s.driver){(s.isResponding||s.bufferedPrompts.length>0)&&(T.info({sessionId:r,agent:s.agent},"interrupting driverless session with stale responding state"),s.bufferedPrompts=[],s.isResponding=!1,s.currentReplyText="",s.lastUserMessage=void 0,s.pendingApproval=void 0,this.markLatestAcceptedClientMessageInterrupted(s),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(s.sessionId,{type:"session.interrupted",sessionId:s.sessionId})),this.reply(e,n,!0);return}if(s.startupInProgress){let i=s.isResponding||s.bufferedPrompts.length>0;T.info({sessionId:r,agent:s.agent,hadBufferedTurn:i},"interrupting pending startup session"),s.bufferedPrompts=[],s.isResponding=!1,s.currentReplyText="",s.lastUserMessage=void 0,s.pendingApproval=void 0,i&&this.markLatestAcceptedClientMessageInterrupted(s),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0),i&&this.broadcast(s.sessionId,{type:"session.interrupted",sessionId:s.sessionId});return}s.driver.interrupt(),this.reply(e,n,!0)}stopSession(e,n,r){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found");return}T.info({sessionId:r,agent:s.agent},"stopping session"),k.emit("session.stop",{sessionId:r,agent:s.agent}),Xp(s);let i=s.isResponding||s.bufferedPrompts.length>0||s.startupInProgress;this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.active=!1,s.driver=null,s.isResponding=!1,s.currentReplyText="",s.pendingApproval=void 0,s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,i&&this.markLatestAcceptedClientMessageInterrupted(s),this.updateGauges(),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0)}deleteSession(e,n,r){let s=this.sessions.get(r);s&&(T.info({sessionId:r,agent:s.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,this.unregisterClaudeHookSession(s),this.sessions.delete(r)),k.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),Us(),Gs(),this.noteInventoryChanged("session_deleted"),this.reply(e,n,!0)}async sendHistory(e,n,r,s){let i=this.sessions.get(r),o=i?.active?i:void 0;if(!i&&this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}i&&i.clients.add(e);let a=o?.cwd??i?.cwd??this.store.find(r)?.cwd??"",l=this.store.find(r),c=await gr(r,s,a),u=this.annotateHistoryMessages(c,i?.acceptedClientMessageIds??l?.acceptedClientMessageIds,i?.interruptedClientMessageIds??l?.interruptedClientMessageIds),d=o||i?{}:await ja(r,s,a),f=o?.isResponding??d.isResponding,p=o?this.currentPartialReplyText(o):d.partialReplyText;T.info({sessionId:r,historyCount:c.length,isResponding:f,approvalMode:i?.approvalMode??l?.approvalMode},"sending history");let g={type:"session.history",sessionId:r,messages:u,...Ks(i?.acceptedClientMessageIds??l?.acceptedClientMessageIds),isResponding:f,partialReplyText:p,approvalMode:i?.approvalMode??l?.approvalMode,pendingApproval:i?.pendingApproval??l?.pendingApproval};e.readyState===1&&e.send(JSON.stringify(g)),this.reply(e,n,!0)}async listSessions(e,n,r,s,i,o=50,a,l){try{let c=await Bs({agent:r,cwd:s,search:i,customTitles:l,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()});this.reply(e,n,!0,{...c,inventoryVersion:this.inventoryVersion})}catch(c){this.reply(e,n,!1,void 0,String(c))}}createDriver(e){switch(e){case"claude":return new Qn;case"codex":return new Xn;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let r=this.sessions.get(e);if(!r){T.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let s=JSON.stringify(n),i=n.type==="approval.request"?this.globalClients:r.clients,o=i.size,a=0,l=0;for(let c of i)c.readyState===1?(c.send(s),a++):l++;if(l>0&&R.increment("broadcast.fail"),n.type!=="text.delta"&&T.debug({sessionId:e,msgType:n.type,sent:a,total:o},"broadcast"),n.type==="text.delta"){r.currentReplyText+=n.content;return}if(n.type==="session.done"){let c=r.title||e,u=this.buildPushBody(r.currentReplyText);r.currentReplyText="",this.pushSender(c,u,{sessionId:e,agent:r.agent,eventType:"reply_ready"});return}n.type==="session.interrupted"&&(r.currentReplyText="")}reply(e,n,r,s,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:r,data:s,error:i};e.send(JSON.stringify(o))}};function Ja(t,e){if(!e.deviceId){e.respond({type:"response",id:t.id,ok:!1,error:"device_auth_required"});return}t.action==="push.register"?e.registerToken(e.deviceId,t.pushToken):e.unregisterToken(e.deviceId,t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var rg=require("child_process");function VA(t,e){return(0,rg.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function zA(t){let e=t.split(`
102
- `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function sg(t,e=VA){let n;try{n=zA(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(r=>{try{let s=e("ps",["-p",String(r),"-o","command="]);return s?{pid:r,command:s}:{pid:r}}catch{return{pid:r}}})}var bn=require("fs"),Qa=require("os"),og=require("crypto"),ag=require("path");function lg(t){return(0,og.randomBytes)(t).toString("base64url")}function YA(){return`d_${lg(12)}`}function KA(){return(0,Qa.hostname)()}function JA(){let t=(0,Qa.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function QA(t){return{daemonId:YA(),daemonSecret:lg(32),displayName:KA(),canonicalHost:JA(),port:t,createdAt:new Date().toISOString()}}function ig(t,e){(0,bn.mkdirSync)((0,ag.dirname)(e),{recursive:!0}),(0,bn.writeFileSync)(e,JSON.stringify(t,null,2)+`
103
- `,"utf8")}function cg(t,e=bd){try{let r=(0,bn.readFileSync)(e,"utf8"),s=JSON.parse(r);if(typeof s.daemonId=="string"&&typeof s.daemonSecret=="string"&&typeof s.displayName=="string"&&typeof s.canonicalHost=="string"&&typeof s.createdAt=="string"){let i={daemonId:s.daemonId,daemonSecret:s.daemonSecret,displayName:s.displayName,canonicalHost:s.canonicalHost,port:typeof s.port=="number"&&Number.isFinite(s.port)?s.port:t,createdAt:s.createdAt};return i.port!==t&&(i.port=t,ig(i,e)),i}}catch{}let n=QA(t);return ig(n,e),n}var An=require("crypto"),En=require("fs"),dg=require("path");function Xa(t){return(0,An.randomBytes)(t).toString("base64url")}function Za(t){return(0,An.createHash)("sha256").update(t).digest("hex")}function ug(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,An.timingSafeEqual)(n,r)}function XA(t){try{let e=(0,En.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.deviceId=="string"&&typeof r.deviceName=="string"&&typeof r.tokenHash=="string"&&typeof r.createdAt=="string"&&typeof r.lastSeenAt=="string"&&(typeof r.revokedAt=="string"||r.revokedAt===null)):[]}catch{return[]}}function _r(t,e){(0,En.mkdirSync)((0,dg.dirname)(t),{recursive:!0}),(0,En.writeFileSync)(t,JSON.stringify(e,null,2)+`
104
- `,"utf8")}var Qs=class{constructor(e=Ad){this.pairingsPath=e;this.records=XA(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4,n=!1){let r=`pair_${Xa(8)}`,s=Xa(24),i=new Date(Date.now()+e).toISOString(),o={pairingId:r,pairNonce:s,expiresAt:i,reusable:n};return this.windows.set(s,o),o}consumeWindow(e){let n=this.windows.get(e);return!n||(n.reusable||this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),s=Xa(32),i={deviceId:e,deviceName:n,tokenHash:Za(s),createdAt:r,lastSeenAt:r,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),_r(this.pairingsPath,this.records),s}validatePairToken(e,n,r=!0){let s=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!s)return!1;let i=Za(n);return ug(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),_r(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=Za(e),s=this.records.find(i=>!i.revokedAt&&ug(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),_r(this.pairingsPath,this.records)),s):null}revoke(e){let n=this.records.find(r=>r.deviceId===e&&!r.revokedAt);return n?(n.revokedAt=new Date().toISOString(),_r(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),_r(this.pairingsPath,this.records)}};function Ut(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function ZA(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function el(t,e){return ZA(t)??e}function Xs(t,e){return!!(t&&e&&t===e)}function tl(t,e,n,r=!0){return t?Xs(t,e)?!0:!!n(t,r):!1}var pg=require("child_process");function Zs(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function nl(t){if(!Zs(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function eE(t){if(!Zs(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function tE(t){if(!Zs(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function nE(t){if(!Zs(t))return!1;let[e,n]=t.split(".").map(Number);return e===10||e===172&&n>=16&&n<=31||e===192&&n===168}function ei(t){return!!t&&!eE(t)&&!tE(t)}function He(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function rl(t){return He(t.replace(/^https?:\/\//,""))??t}function rE(t,e){return(t??[]).map(n=>He(n)).filter(n=>!!n).filter(n=>ei(n)).filter((n,r,s)=>n!==e&&s.indexOf(n)===r)}function sE(t){let e=rl(t);return nl(e)||e.endsWith(".ts.net")}function iE(t){let e=rl(t);return nE(e)||e.endsWith(".local")}function oE(t){return rl(t).endsWith(".trycloudflare.com")}function fg(t,e){return sE(t)?"tailscale":iE(t)?"local_network":e?"configured_host":"fallback"}function gg(t){let e=new Set,n=[];for(let r of t){let s=`${r.host}:${r.port}`;e.has(s)||(e.add(s),n.push(r))}return n}function aE(t){let e=t[0];return e?t.slice(1).filter(n=>n.port===e.port).map(n=>n.host).filter((n,r,s)=>n!==e.host&&s.indexOf(n)===r):[]}function lE(t){try{let e=new URL(t),n=He(e.hostname);if(!n)throw new Error("invalid relay hostname");let r=e.port?Number(e.port):e.protocol==="https:"?443:80,s=Number.isFinite(r)&&r>0?Math.floor(r):443,i=oE(n);return{kind:"relay",host:n,port:s,source:i?"quick_tunnel":"configured_relay",stability:i?"ephemeral":"stable"}}catch{return null}}function cE(t,e,n){let r=He(t)||"localhost",s=rE(e,r);return gg([{kind:"direct",host:r,port:n,source:fg(r,!0),stability:"stable"},...s.map(i=>({kind:"direct",host:i,port:n,source:fg(i,!1),stability:"stable"}))])}function mg(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function uE(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let s of r)s.internal||s.family!=="IPv4"||ei(s.address)&&(nl(s.address)?e.push(s.address):n.push(s.address));return[...e,...n]}function hg(t){let e=JSON.parse(t),n=He(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>He(o)).filter(o=>!!o).filter(o=>nl(o)&&ei(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function yg(t=pg.execFileSync){let e=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(Boolean);for(let n of e)try{let r=t("tailscale",["--socket",n,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return hg(r)}catch{}try{let n=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return hg(n)}catch{return{fallbackHosts:[]}}}function _g(t){let e=cE(t.canonicalHost,t.fallbackHosts,t.port),n=t.relayUrl?lE(t.relayUrl):null,r=gg([...n?[n]:[],...e]),s=r[0]??{kind:"direct",host:He(t.canonicalHost)||"localhost",port:t.port,source:"configured_host",stability:"stable"};return{canonicalHost:s.host,fallbackHosts:aE(r),port:s.port,connections:r}}function Sg(t){let e=He(t.canonicalHost),n=He(t.configuredCanonicalHost)||He(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...uE(t.interfaces)].map(s=>He(s)).filter(s=>!!s).filter(s=>ei(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function vg(t){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("utf8");if(Array.isArray(t))return Buffer.concat(t).toString("utf8");if(t instanceof ArrayBuffer)return Buffer.from(t).toString("utf8");if(ArrayBuffer.isView(t)){let e=t;return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}return String(t)}var de=K.child({module:"daemon"}),Sr=K.child({module:"ws"});function dE(){try{let t=JSON.parse(require("fs").readFileSync(Id,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var oe=cg(C.port),Ie=new Js((t,e,n)=>Ys(t,e,{daemonId:oe.daemonId,canonicalHost:vr().canonicalHost,...n??{}})),Fe=new Qs,ni=new Set,yt=new WeakMap,wg=!1,Ig=Date.now(),In=null,ti=null,fE=1e3;function hE(){let t=yg();return Sg({canonicalHost:oe.canonicalHost,configuredCanonicalHost:C.canonicalHost,configuredFallbackHosts:mg(C.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Eg.networkInterfaces)()})}function vr(){let t=Date.now();if(ti&&ti.expiresAt>t)return ti.value;let e=hE(),n=_g({canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:oe.port,relayUrl:C.relayUrl});return ti={value:n,expiresAt:t+fE},n}function pE(t){let e={t:"vp",d:t.daemonId,n:t.displayName,h:t.canonicalHost,p:t.port,c:t.pairNonce,e:t.expiresAt};return t.fallbackHosts&&(e.f=t.fallbackHosts),t.connections?.length&&(e.o=t.connections.map(n=>[n.kind,n.host,n.port,n.source,n.stability])),e}async function gE(t){let e=JSON.stringify(pE(t));await(0,Me.mkdir)(Xe,{recursive:!0}),await ol.default.toFile(_o,e,{type:"png",errorCorrectionLevel:"M",margin:1,scale:8});let n=await ol.default.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"M"});sn(`
100
+ ${u}`:u:s;if(l!==void 0&&(c.model=l||void 0),c.startupInProgress){c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,c.bufferedPrompts.push(d),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}if(c.isResponding){c.bufferedPrompts.push(d),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}c.isResponding=!0,c.currentReplyText="",c.lastUserMessage=s,this.noteInventoryChanged("session_updated"),c.driver.sendPrompt(d,c.model),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0)}async sendReconnectSnapshot(e,n,r,s,i,o,a,l){try{let c=this.getDeletedSessionIds(),u;try{u=await gr({agent:r,cwd:s,search:i,customTitles:l,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:c})}catch(h){_.warn({error:String(h)},"failed to build reconnect snapshot session list"),u={sessions:[],nextCursor:void 0}}u={...u,inventoryVersion:this.inventoryVersion};let d;if(o&&!c.has(o)){let h=a??u.sessions.find(m=>m.sessionId===o)?.agent,g=this.sessions.get(o);g&&g.clients.add(e);let p=await this.resolveReconnectSession(o,h,g);if(p){let m=await yn(o,p.agent,g?.cwd??p.cwd),v=this.annotateHistoryMessages(m,g?.acceptedClientMessageIds??p.acceptedClientMessageIds,g?.interruptedClientMessageIds??p.interruptedClientMessageIds),b=g?{}:await Ai(o,p.agent,p.cwd);d={sessionId:o,agent:p.agent,messages:v,...xr(g?.acceptedClientMessageIds??p.acceptedClientMessageIds),isResponding:g?.isResponding??b.isResponding??p.isResponding,partialReplyText:g?this.currentPartialReplyText(g):b.partialReplyText,approvalMode:g?.approvalMode??p.approvalMode,...g?.pendingApproval?{pendingApproval:g.pendingApproval}:{}}}}let f=this.collectReconnectPendingApprovals();w.increment("reconnect.snapshot",{activeSession:d?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:u.sessions,nextCursor:u.nextCursor,inventoryVersion:u.inventoryVersion,...d?{activeSession:d}:{},...f.length>0?{pendingApprovals:f}:{}}})}catch(c){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(c)}`)}}async approve(e,n,r,s,i){let o=this.sessions.get(r),a=o?.pendingApproval,l=o?.pendingClaudeHookApprovals.get(s);if(o&&l){o.pendingApproval=void 0,I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),l.resolve(Du(i)),o.isResponding=!0,this.reply(e,n,!0);return}let c=o?.syntheticApprovalRetries[s];if(o&&c&&lr(s)){delete o.syntheticApprovalRetries[s],o.pendingApproval=void 0,I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0),i&&await this.retrySyntheticClaudeApproval(o,c);return}if(o&&!o.driver&&a)try{await this.reviveSessionForApproval(o)}catch(d){this.reply(e,n,!1,void 0,`Failed to restore approval session: ${String(d)}`);return}if(!o?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(I.emit("approval.response",{sessionId:r,requestId:s,approved:i}),!o.driver.respondApproval(s,i)){this.reply(e,n,!1,void 0,"Agent process is not running. Send a new message to continue.");return}o.pendingApproval=void 0,this.touchSession(o.sessionId),o.isResponding=!0,this.noteInventoryChanged("session_updated"),this.reply(e,n,!0)}async retrySyntheticClaudeApproval(e,n){if(e.agent==="claude")try{e.driver&&e.driver.stop();let r=["Write","Edit","NotebookEdit"].includes(n.toolName)?"acceptEdits":"autoApprove",s=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,s,e.claudeHookSecret);await s.start(e.cwd,e.sessionId,r),e.driver=s,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n.message,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken=0,e.claudeHookSecret=i??e.claudeHookSecret,e.pendingClaudeHookApprovals=e.pendingClaudeHookApprovals??new Map,this.registerClaudeHookSession(e),this.bindDriverLifecycle(e,e.agent," (approval retry)"),this.store.upsert(he(e)),this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),_.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),s.sendPrompt(n.message,e.model)}catch(r){e.driver=null,e.active=!1,e.isResponding=!1,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken+=1,this.updateGauges(),this.touchSession(e.sessionId),this.noteInventoryChanged("session_updated"),_.error({sessionId:e.sessionId,error:String(r)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(r)}`})}}async setApprovalMode(e,n,r,s){let i=this.sessions.get(r);if(!i){let a=this.store.find(r);a?(s===null?delete a.approvalMode:a.approvalMode=s,this.store.upsert(a),this.noteInventoryChanged("session_updated"),_.info({sessionId:r,agent:a.agent,newMode:s},"approval mode changed (inactive session)")):_.info({sessionId:r,newMode:s},"approval mode changed (untracked session)"),this.reply(e,n,!0,{approvalMode:s});return}if(s===null){this.reply(e,n,!1,void 0,"Follow Remote is only available for external sessions");return}let o=i.approvalMode;i.approvalMode=s,this.store.upsert(he(i)),this.noteInventoryChanged("session_updated"),_.info({sessionId:r,agent:i.agent,oldMode:o,newMode:s},"approval mode changed"),i.driver&&i.driver.setApprovalMode(s),this.reply(e,n,!0,{approvalMode:s})}interrupt(e,n,r){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found or inactive");return}if(I.emit("session.interrupt",{sessionId:r,agent:s.agent}),!s.driver){(s.isResponding||s.bufferedPrompts.length>0)&&(_.info({sessionId:r,agent:s.agent},"interrupting driverless session with stale responding state"),s.bufferedPrompts=[],s.isResponding=!1,s.currentReplyText="",s.lastUserMessage=void 0,s.pendingApproval=void 0,this.markLatestAcceptedClientMessageInterrupted(s),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.broadcast(s.sessionId,{type:"session.interrupted",sessionId:s.sessionId})),this.reply(e,n,!0);return}if(s.startupInProgress){let i=s.isResponding||s.bufferedPrompts.length>0;_.info({sessionId:r,agent:s.agent,hadBufferedTurn:i},"interrupting pending startup session"),s.bufferedPrompts=[],s.isResponding=!1,s.currentReplyText="",s.lastUserMessage=void 0,s.pendingApproval=void 0,i&&this.markLatestAcceptedClientMessageInterrupted(s),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0),i&&this.broadcast(s.sessionId,{type:"session.interrupted",sessionId:s.sessionId});return}s.driver.interrupt(),this.reply(e,n,!0)}stopSession(e,n,r){let s=this.sessions.get(r);if(!s){this.reply(e,n,!1,void 0,"Session not found");return}_.info({sessionId:r,agent:s.agent},"stopping session"),I.emit("session.stop",{sessionId:r,agent:s.agent}),Nu(s);let i=s.isResponding||s.bufferedPrompts.length>0||s.startupInProgress;this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.active=!1,s.driver=null,s.isResponding=!1,s.currentReplyText="",s.pendingApproval=void 0,s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,i&&this.markLatestAcceptedClientMessageInterrupted(s),this.updateGauges(),this.touchSession(s.sessionId),this.noteInventoryChanged("session_updated"),this.reply(e,n,!0)}deleteSession(e,n,r){let s=this.sessions.get(r);s&&(_.info({sessionId:r,agent:s.agent},"deleting session"),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,this.unregisterClaudeHookSession(s),this.sessions.delete(r)),I.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),yr(),br(),this.noteInventoryChanged("session_deleted"),this.reply(e,n,!0)}async sendHistory(e,n,r,s){let i=this.sessions.get(r),o=i?.active?i:void 0;if(!i&&this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}i&&i.clients.add(e);let a=o?.cwd??i?.cwd??this.store.find(r)?.cwd??"",l=this.store.find(r),c=await yn(r,s,a),u=this.annotateHistoryMessages(c,i?.acceptedClientMessageIds??l?.acceptedClientMessageIds,i?.interruptedClientMessageIds??l?.interruptedClientMessageIds),d=o||i?{}:await Ai(r,s,a),f=o?.isResponding??d.isResponding,h=o?this.currentPartialReplyText(o):d.partialReplyText;_.info({sessionId:r,historyCount:c.length,isResponding:f,approvalMode:i?.approvalMode??l?.approvalMode},"sending history");let g={type:"session.history",sessionId:r,messages:u,...xr(i?.acceptedClientMessageIds??l?.acceptedClientMessageIds),isResponding:f,partialReplyText:h,approvalMode:i?.approvalMode??l?.approvalMode,pendingApproval:i?.pendingApproval??l?.pendingApproval};e.readyState===1&&e.send(JSON.stringify(g)),this.reply(e,n,!0)}async listSessions(e,n,r,s,i,o=50,a,l){try{let c=await gr({agent:r,cwd:s,search:i,customTitles:l,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()});this.reply(e,n,!0,{...c,inventoryVersion:this.inventoryVersion})}catch(c){this.reply(e,n,!1,void 0,String(c))}}createDriver(e){switch(e){case"claude":return new ln;case"codex":return new cn;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,n){let r=this.sessions.get(e);if(!r){_.warn({sessionId:e,msgType:n.type},"broadcast target session not found");return}let s=JSON.stringify(n),i=n.type==="approval.request"?this.globalClients:r.clients,o=i.size,a=0,l=0;for(let c of i)c.readyState===1?(c.send(s),a++):l++;if(l>0&&w.increment("broadcast.fail"),n.type!=="text.delta"&&_.debug({sessionId:e,msgType:n.type,sent:a,total:o},"broadcast"),n.type==="text.delta"){r.currentReplyText+=n.content;return}if(n.type==="session.done"){let c=r.title||e,u=this.buildPushBody(r.currentReplyText);r.currentReplyText="",this.pushSender(c,u,{sessionId:e,agent:r.agent,eventType:"reply_ready"});return}n.type==="session.interrupted"&&(r.currentReplyText="")}reply(e,n,r,s,i){if(e.readyState!==1)return;let o={type:"response",id:n,ok:r,data:s,error:i};e.send(JSON.stringify(o))}};function Ei(t,e){if(!e.deviceId){e.respond({type:"response",id:t.id,ok:!1,error:"device_auth_required"});return}t.action==="push.register"?e.registerToken(e.deviceId,t.pushToken):e.unregisterToken(e.deviceId,t.pushToken),e.respond({type:"response",id:t.id,ok:!0})}var Fu=require("child_process");function vy(t,e){return(0,Fu.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function Sy(t){let e=t.split(`
101
+ `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function Uu(t,e=vy){let n;try{n=Sy(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(r=>{try{let s=e("ps",["-p",String(r),"-o","command="]);return s?{pid:r,command:s}:{pid:r}}catch{return{pid:r}}})}var Mt=require("fs"),Pi=require("os"),Wu=require("crypto"),Gu=require("path");function ju(t){return(0,Wu.randomBytes)(t).toString("base64url")}function _y(){return`d_${ju(12)}`}function by(){return(0,Pi.hostname)()}function wy(){let t=(0,Pi.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function Iy(t){return{daemonId:_y(),daemonSecret:ju(32),displayName:by(),canonicalHost:wy(),port:t,createdAt:new Date().toISOString()}}function qu(t,e){(0,Mt.mkdirSync)((0,Gu.dirname)(e),{recursive:!0}),(0,Mt.writeFileSync)(e,JSON.stringify(t,null,2)+`
102
+ `,"utf8")}function Vu(t,e=nc){try{let r=(0,Mt.readFileSync)(e,"utf8"),s=JSON.parse(r);if(typeof s.daemonId=="string"&&typeof s.daemonSecret=="string"&&typeof s.displayName=="string"&&typeof s.canonicalHost=="string"&&typeof s.createdAt=="string"){let i={daemonId:s.daemonId,daemonSecret:s.daemonSecret,displayName:s.displayName,canonicalHost:s.canonicalHost,port:typeof s.port=="number"&&Number.isFinite(s.port)?s.port:t,createdAt:s.createdAt};return i.port!==t&&(i.port=t,qu(i,e)),i}}catch{}let n=Iy(t);return qu(n,e),n}var Lt=require("crypto"),Nt=require("fs"),zu=require("path");function Ri(t){return(0,Lt.randomBytes)(t).toString("base64url")}function Mi(t){return(0,Lt.createHash)("sha256").update(t).digest("hex")}function $u(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,Lt.timingSafeEqual)(n,r)}function Ay(t){try{let e=(0,Nt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(r=>r&&typeof r.deviceId=="string"&&typeof r.deviceName=="string"&&typeof r.tokenHash=="string"&&typeof r.createdAt=="string"&&typeof r.lastSeenAt=="string"&&(typeof r.revokedAt=="string"||r.revokedAt===null)):[]}catch{return[]}}function _n(t,e){(0,Nt.mkdirSync)((0,zu.dirname)(t),{recursive:!0}),(0,Nt.writeFileSync)(t,JSON.stringify(e,null,2)+`
103
+ `,"utf8")}var kr=class{constructor(e=rc){this.pairingsPath=e;this.records=Ay(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4,n=!1){let r=`pair_${Ri(8)}`,s=Ri(24),i=new Date(Date.now()+e).toISOString(),o={pairingId:r,pairNonce:s,expiresAt:i,reusable:n};return this.windows.set(s,o),o}consumeWindow(e){let n=this.windows.get(e);return!n||(n.reusable||this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),s=Ri(32),i={deviceId:e,deviceName:n,tokenHash:Mi(s),createdAt:r,lastSeenAt:r,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),_n(this.pairingsPath,this.records),s}validatePairToken(e,n,r=!0){let s=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!s)return!1;let i=Mi(n);return $u(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),_n(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=Mi(e),s=this.records.find(i=>!i.revokedAt&&$u(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),_n(this.pairingsPath,this.records)),s):null}revoke(e){let n=this.records.find(r=>r.deviceId===e&&!r.revokedAt);return n?(n.revokedAt=new Date().toISOString(),_n(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),_n(this.pairingsPath,this.records)}};function et(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function Ty(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Li(t,e){return Ty(t)??e}function Er(t,e){return!!(t&&e&&t===e)}function Ni(t,e,n,r=!0){return t?Er(t,e)?!0:!!n(t,r):!1}var Ku=require("child_process");function Pr(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Oi(t){if(!Pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function xy(t){if(!Pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function Cy(t){if(!Pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function ky(t){if(!Pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===10||e===172&&n>=16&&n<=31||e===192&&n===168}function Rr(t){return!!t&&!xy(t)&&!Cy(t)}function ae(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Bi(t){return ae(t.replace(/^https?:\/\//,""))??t}function Ey(t,e){return(t??[]).map(n=>ae(n)).filter(n=>!!n).filter(n=>Rr(n)).filter((n,r,s)=>n!==e&&s.indexOf(n)===r)}function Py(t){let e=Bi(t);return Oi(e)||e.endsWith(".ts.net")}function Ry(t){let e=Bi(t);return ky(e)||e.endsWith(".local")}function My(t){return Bi(t).endsWith(".trycloudflare.com")}function Yu(t,e){return Py(t)?"tailscale":Ry(t)?"local_network":e?"configured_host":"fallback"}function Qu(t){let e=new Set,n=[];for(let r of t){let s=`${r.host}:${r.port}`;e.has(s)||(e.add(s),n.push(r))}return n}function Ly(t){let e=t[0];return e?t.slice(1).filter(n=>n.port===e.port).map(n=>n.host).filter((n,r,s)=>n!==e.host&&s.indexOf(n)===r):[]}function Ny(t){try{let e=new URL(t),n=ae(e.hostname);if(!n)throw new Error("invalid relay hostname");let r=e.port?Number(e.port):e.protocol==="https:"?443:80,s=Number.isFinite(r)&&r>0?Math.floor(r):443,i=My(n);return{kind:"relay",host:n,port:s,source:i?"quick_tunnel":"configured_relay",stability:i?"ephemeral":"stable"}}catch{return null}}function Oy(t,e,n){let r=ae(t)||"localhost",s=Ey(e,r);return Qu([{kind:"direct",host:r,port:n,source:Yu(r,!0),stability:"stable"},...s.map(i=>({kind:"direct",host:i,port:n,source:Yu(i,!1),stability:"stable"}))])}function Xu(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function By(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let s of r)s.internal||s.family!=="IPv4"||Rr(s.address)&&(Oi(s.address)?e.push(s.address):n.push(s.address));return[...e,...n]}function Ju(t){let e=JSON.parse(t),n=ae(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>ae(o)).filter(o=>!!o).filter(o=>Oi(o)&&Rr(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function Zu(t=Ku.execFileSync){let e=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(Boolean);for(let n of e)try{let r=t("tailscale",["--socket",n,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Ju(r)}catch{}try{let n=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return Ju(n)}catch{return{fallbackHosts:[]}}}function ed(t){let e=Oy(t.canonicalHost,t.fallbackHosts,t.port),n=t.relayUrl?Ny(t.relayUrl):null,r=Qu([...n?[n]:[],...e]),s=r[0]??{kind:"direct",host:ae(t.canonicalHost)||"localhost",port:t.port,source:"configured_host",stability:"stable"};return{canonicalHost:s.host,fallbackHosts:Ly(r),port:s.port,connections:r}}function td(t){let e=ae(t.canonicalHost),n=ae(t.configuredCanonicalHost)||ae(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...By(t.interfaces)].map(s=>ae(s)).filter(s=>!!s).filter(s=>Rr(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function nd(t){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("utf8");if(Array.isArray(t))return Buffer.concat(t).toString("utf8");if(t instanceof ArrayBuffer)return Buffer.from(t).toString("utf8");if(ArrayBuffer.isView(t)){let e=t;return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}return String(t)}var q=P.child({module:"daemon"}),bn=P.child({module:"ws"});function Dy(){try{let t=JSON.parse(require("fs").readFileSync(ic,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var D=Vu(S.port),J=new Cr((t,e,n)=>Tr(t,e,{daemonId:D.daemonId,canonicalHost:wn().canonicalHost,...n??{}})),ce=new kr,Lr=new Set,De=new WeakMap,rd=!1,ad=Date.now(),Ot=null,Mr=null,Hy=1e3;function Fy(){let t=Zu();return td({canonicalHost:D.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:Xu(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,od.networkInterfaces)()})}function wn(){let t=Date.now();if(Mr&&Mr.expiresAt>t)return Mr.value;let e=Fy(),n=ed({canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:D.port,relayUrl:S.relayUrl});return Mr={value:n,expiresAt:t+Hy},n}function Uy(t){let e={t:"vp",d:t.daemonId,n:t.displayName,h:t.canonicalHost,p:t.port,c:t.pairNonce,e:t.expiresAt};return t.fallbackHosts&&(e.f=t.fallbackHosts),t.connections?.length&&(e.o=t.connections.map(n=>[n.kind,n.host,n.port,n.source,n.stability])),e}async function qy(t){let e=JSON.stringify(Uy(t));await(0,re.mkdir)(_e,{recursive:!0}),await Fi.default.toFile(Ys,e,{type:"png",errorCorrectionLevel:"M",margin:1,scale:8});let n=await Fi.default.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"M"});_t(`
105
104
  Scan this QR code with Vibelet app:
106
105
 
107
106
  ${n}
108
- `),sn(`If Vibelet app can't scan the terminal QR, open this PNG instead:
109
- ${_o}
110
- `)}async function sl(t){let e=[];for await(let r of t)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function te(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function mE(t){let e=(0,wr.extname)(t).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".md":"text/markdown; charset=utf-8",".markdown":"text/markdown; charset=utf-8",".txt":"text/plain; charset=utf-8",".log":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8",".js":"text/plain; charset=utf-8",".jsx":"text/plain; charset=utf-8",".ts":"text/plain; charset=utf-8",".tsx":"text/plain; charset=utf-8",".mjs":"text/plain; charset=utf-8",".cjs":"text/plain; charset=utf-8",".css":"text/plain; charset=utf-8",".html":"text/plain; charset=utf-8",".yml":"text/plain; charset=utf-8",".yaml":"text/plain; charset=utf-8"}[e]||"application/octet-stream"}function xg(){return C.pairWindowMs===0?10*365.25*24*36e5:C.pairWindowMs}function yE(t,e){if(Ut(t.socket.remoteAddress))return!0;let n=el(t.headers.authorization,e.searchParams.get("token"));return tl(n,C.legacyToken,(r,s)=>Fe.validateAnyPairToken(r,s),!1)}function _E(){let t=Fe.openWindow(xg(),C.pairReusable),e=vr();return{type:"vibelet-pair",daemonId:oe.daemonId,displayName:oe.displayName,canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts.length>0?e.fallbackHosts:void 0,port:e.port,connections:e.connections,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function SE(t,e){let n=Va(t,e),r=await(0,Me.readdir)(n),s=[];for(let i of r){if(i.startsWith("."))continue;let o=await(0,Me.stat)((0,wr.join)(n,i)).catch(()=>null);o&&s.push({name:i,isDirectory:o.isDirectory()})}return s.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:s}}var br=(0,bg.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${C.port}`);if(n.pathname==="/health"){let s=vr(),i=dE(),o={status:"ok",version:an,...i?{latestVersion:i}:{}};if(!yE(t,n)){te(e,200,o);return}let a={...o,status:"ok",daemonId:oe.daemonId,displayName:oe.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-Ig)/1e3),activeSessions:Ie.getActiveSessionCount(),pairedDevices:Fe.pairedCount(),wsClients:Be.clients.size,drivers:Ie.getDriverCounts(),sessionInventory:Sp(),metrics:R.snapshot()};C.relayUrl&&(a.relayUrl=C.relayUrl),te(e,200,a);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!Ut(t.socket.remoteAddress)){te(e,403,{error:"forbidden"});return}te(e,200,_E());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!Ut(t.socket.remoteAddress)){te(e,403,{error:"forbidden"});return}Fe.reset(),te(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!Ut(t.socket.remoteAddress)){te(e,403,{error:"forbidden"});return}te(e,200,{status:"stopping"}),setTimeout(()=>qt("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!Ut(t.socket.remoteAddress)){te(e,403,{error:"forbidden"});return}try{let s=await sl(t),i=t.headers[Kn],o=Array.isArray(i)?i[0]:i;Ie.handleClaudeSessionStartHook(o,s),te(e,200,{ok:!0})}catch(s){te(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!Ut(t.socket.remoteAddress)){te(e,403,{error:"forbidden"});return}try{let s=await sl(t),i=t.headers[Kn],o=Array.isArray(i)?i[0]:i,a=await Ie.handleClaudePermissionHook(o,s);te(e,200,a)}catch(s){te(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let s=await sl(t);if(s.daemonId!==oe.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){te(e,400,{error:"invalid_pair_request"});return}if(!Fe.consumeWindow(s.pairNonce)){te(e,401,{error:"pair_window_expired"});return}let o=Fe.issuePairToken(s.deviceId,s.deviceName),a=vr();te(e,200,{daemonId:oe.daemonId,displayName:oe.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:a.port,connections:a.connections,deviceId:s.deviceId,pairToken:o})}catch(s){te(e,400,{error:String(s)})}return}let r=el(t.headers.authorization,n.searchParams.get("token"));if(!tl(r,C.legacyToken,(s,i)=>Fe.validateAnyPairToken(s,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(t.method==="POST"&&n.pathname==="/upload"){let s={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/heif":".heif"},i=(t.headers["content-type"]??"").split(";")[0].trim(),o=s[i];if(!o){te(e,400,{error:"Unsupported content type"});return}let a=10*1024*1024,l=[],c=0;for await(let u of t){let d=Buffer.isBuffer(u)?u:Buffer.from(u);if(c+=d.length,c>a){e.writeHead(413),e.end("File too large");return}l.push(d)}try{await(0,Me.mkdir)(yo,{recursive:!0});let u=`${Date.now()}_${(0,Ag.randomBytes)(8).toString("hex")}${o}`,d=(0,wr.join)(yo,u);await(0,Me.writeFile)(d,Buffer.concat(l)),de.info({filePath:d,size:c},"file uploaded"),te(e,200,{path:d})}catch(u){de.error({error:String(u)},"upload failed"),te(e,500,{error:"Upload failed"})}return}if(n.pathname==="/file"){let s=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!s){e.writeHead(400),e.end("Missing path parameter");return}try{let o=Va(s,i);if(!(await(0,Me.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=mE(o),c=await(0,Me.readFile)(o);e.writeHead(200,{"Content-Type":l,"Content-Length":c.length}),e.end(c)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${an}`)}),Be=new Ii.default({server:br});br.on("connection",t=>{ni.add(t),t.on("close",()=>{ni.delete(t)})});Be.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${C.port}`).searchParams.get("token");if(r&&Xs(r,C.legacyToken))yt.set(t,{authMode:"query_token"}),R.increment("ws.auth.success",{mode:"query_token"}),Ie.addGlobalClient(t),Ie.prewarmCaches();else if(r){let s=Fe.validateAnyPairToken(r);if(s)yt.set(t,{authMode:"query_token",deviceId:s.deviceId}),R.increment("ws.auth.success",{mode:"query_token"}),Ie.addGlobalClient(t),Ie.prewarmCaches();else{R.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}}Sr.info({clients:Be.clients.size},"client connected"),R.increment("ws.connect"),R.gauge("ws.clients",Be.clients.size),k.emit("ws.connect",{clients:Be.clients.size,authMode:yt.get(t)?.authMode??"pending",deviceId:yt.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(vg(s));if(!i||typeof i.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(i.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let o=i;if(!yt.has(t)){if(o.action==="auth.hello"){let a=(()=>{if(Xs(o.pairToken,C.legacyToken))return{deviceId:o.deviceId};if(o.deviceId&&o.daemonId===oe.daemonId&&Fe.validatePairToken(o.deviceId,o.pairToken))return{deviceId:o.deviceId};if(!o.daemonId||o.daemonId===oe.daemonId){let l=Fe.validateAnyPairToken(o.pairToken);if(l)return{deviceId:l.deviceId}}return null})();if(a){yt.set(t,{authMode:"auth_hello",deviceId:a.deviceId}),R.increment("ws.auth.success",{mode:"auth_hello"}),Ie.addGlobalClient(t),Ie.prewarmCaches(),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:oe.daemonId,displayName:oe.displayName}}));return}R.increment("ws.auth.failure",{mode:"auth_hello"}),t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}R.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(o.action==="log.report"){for(let a of o.entries)k.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?de.error:a.level==="warn"?de.warn:de.info).call(de,{event:a.event,...a.data},`[app] ${a.event}`);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await SE(o.path,o.cwd);t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:a}))}catch(a){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:String(a)}))}return}if(i.action==="push.register"){let a=yt.get(t);Ja(i,{deviceId:a?.deviceId,registerToken:za,unregisterToken:Ya,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=yt.get(t);Ja(i,{deviceId:a?.deviceId,registerToken:za,unregisterToken:Ya,respond:l=>t.send(JSON.stringify(l))});return}await Ie.handle(t,o)}catch(i){Sr.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{Sr.info({clients:Be.clients.size,code:s},"client disconnected"),R.increment("ws.disconnect"),R.increment("ws.disconnect.code",{code:String(s)}),R.gauge("ws.clients",Be.clients.size),k.emit("ws.disconnect",{clients:Be.clients.size,code:s}),Ie.removeClient(t)}),t.on("error",s=>{Sr.error({error:s.message},"websocket error")})});function il(){for(let t of ni)try{t.destroy()}catch{}ni.clear()}function Cg(){let t=Dd({auditPath:rn,stdoutLogPath:rs,stderrLogPath:ss,auditMaxBytes:C.auditMaxBytes,logMaxBytes:C.daemonLogMaxBytes});t.trimmedFiles>0&&de.info({trimmedFiles:t.trimmedFiles,reclaimedBytes:t.reclaimedBytes,files:t.files.filter(e=>e.trimmed).map(e=>({path:e.path,beforeBytes:e.beforeBytes,afterBytes:e.afterBytes}))},"trimmed vibelet storage")}function vE(){In||(In=setInterval(Cg,C.storageHousekeepingIntervalMs),In.unref())}function wE(){In&&(clearInterval(In),In=null)}function qt(t,e=0){if(!wg){wg=!0,de.info({reason:t,exitCode:e},"shutting down"),k.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-Ig)/1e3)}),R.stopPeriodicLog(),wE(),pn.stop().catch(()=>{}),Ie.shutdown();for(let n of Be.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}Be.close(n=>{n&&de.error({error:String(n)},"websocket close error")}),br.close(n=>{if(n){de.error({error:String(n)},"http close error"),il(),process.exit(1);return}il(),process.exit(e)}),setTimeout(()=>{de.error("force exiting after shutdown timeout"),il(),process.exit(e||1)},3e3).unref()}}Be.on("error",t=>{Sr.error({error:t.message},"wss error")});br.on("error",t=>{if(t.code==="EADDRINUSE"){let e=sg(C.port).filter(n=>n.pid!==process.pid);de.error({port:C.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else de.error({error:String(t)},"server error");qt(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>qt("SIGINT"));process.once("SIGTERM",()=>qt("SIGTERM"));process.once("SIGHUP",()=>qt("SIGHUP"));process.once("SIGTTIN",()=>qt("SIGTTIN"));process.once("SIGTSTP",()=>qt("SIGTSTP"));process.on("uncaughtException",t=>{de.error({error:String(t),stack:t.stack},"uncaughtException"),k.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{de.error({reason:String(t)},"unhandledRejection"),k.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});br.listen(C.port,async()=>{Cg(),k.emit("daemon.start",{port:C.port}),R.startPeriodicLog(),vE(),vp(),pn.start().catch(r=>{de.warn({error:String(r)},"session activity watcher failed to start")});let t=vr();de.info({port:C.port,pairingPort:t.port,daemonId:oe.daemonId,displayName:oe.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts,claudePath:C.claudePath,codexPath:C.codexPath,auditMaxBytes:C.auditMaxBytes,daemonLogMaxBytes:C.daemonLogMaxBytes,storageHousekeepingIntervalMs:C.storageHousekeepingIntervalMs,turnStallTimeoutMs:C.turnStallTimeoutMs},"daemon started");let e=Fe.openWindow(xg(),C.pairReusable),n={type:"vibelet-pair",daemonId:oe.daemonId,displayName:oe.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts.length>0?t.fallbackHosts:void 0,port:t.port,connections:t.connections,pairNonce:e.pairNonce,expiresAt:e.expiresAt};sn(`
107
+ `),_t(`If Vibelet app can't scan the terminal QR, open this PNG instead:
108
+ ${Ys}
109
+ `)}async function Di(t){let e=[];for await(let r of t)e.push(Buffer.isBuffer(r)?r:Buffer.from(r));let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):{}}function N(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function Wy(t){let e=(0,In.extname)(t).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".md":"text/markdown; charset=utf-8",".markdown":"text/markdown; charset=utf-8",".txt":"text/plain; charset=utf-8",".log":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8",".js":"text/plain; charset=utf-8",".jsx":"text/plain; charset=utf-8",".ts":"text/plain; charset=utf-8",".tsx":"text/plain; charset=utf-8",".mjs":"text/plain; charset=utf-8",".cjs":"text/plain; charset=utf-8",".css":"text/plain; charset=utf-8",".html":"text/plain; charset=utf-8",".yml":"text/plain; charset=utf-8",".yaml":"text/plain; charset=utf-8"}[e]||"application/octet-stream"}function ld(){return S.pairWindowMs===0?10*365.25*24*36e5:S.pairWindowMs}function Gy(t,e){if(et(t.socket.remoteAddress))return!0;let n=Li(t.headers.authorization,e.searchParams.get("token"));return Ni(n,S.legacyToken,(r,s)=>ce.validateAnyPairToken(r,s),!1)}function jy(){let t=ce.openWindow(ld(),S.pairReusable),e=wn();return{type:"vibelet-pair",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts.length>0?e.fallbackHosts:void 0,port:e.port,connections:e.connections,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function Vy(t,e){let n=Ti(t,e),r=await(0,re.readdir)(n),s=[];for(let i of r){if(i.startsWith("."))continue;let o=await(0,re.stat)((0,In.join)(n,i)).catch(()=>null);o&&s.push({name:i,isDirectory:o.isDirectory()})}return s.sort((i,o)=>i.isDirectory!==o.isDirectory?i.isDirectory?-1:1:i.name.localeCompare(o.name)),{entries:s}}var An=(0,sd.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${S.port}`);if(n.pathname==="/health"){let s=wn(),i=Dy(),o={status:"ok",version:wt,...i?{latestVersion:i}:{}};if(!Gy(t,n)){N(e,200,o);return}let a={...o,status:"ok",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-ad)/1e3),activeSessions:J.getActiveSessionCount(),pairedDevices:ce.pairedCount(),wsClients:le.clients.size,drivers:J.getDriverCounts(),sessionInventory:tu(),metrics:w.snapshot()};S.relayUrl&&(a.relayUrl=S.relayUrl),N(e,200,a);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!et(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}N(e,200,jy());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!et(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}ce.reset(),N(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!et(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}N(e,200,{status:"stopping"}),setTimeout(()=>tt("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!et(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}try{let s=await Di(t),i=t.headers[on],o=Array.isArray(i)?i[0]:i;J.handleClaudeSessionStartHook(o,s),N(e,200,{ok:!0})}catch(s){N(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!et(t.socket.remoteAddress)){N(e,403,{error:"forbidden"});return}try{let s=await Di(t),i=t.headers[on],o=Array.isArray(i)?i[0]:i,a=await J.handleClaudePermissionHook(o,s);N(e,200,a)}catch(s){N(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let s=await Di(t);if(s.daemonId!==D.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){N(e,400,{error:"invalid_pair_request"});return}if(!ce.consumeWindow(s.pairNonce)){N(e,401,{error:"pair_window_expired"});return}let o=ce.issuePairToken(s.deviceId,s.deviceName),a=wn();N(e,200,{daemonId:D.daemonId,displayName:D.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:a.port,connections:a.connections,deviceId:s.deviceId,pairToken:o})}catch(s){N(e,400,{error:String(s)})}return}let r=Li(t.headers.authorization,n.searchParams.get("token"));if(!Ni(r,S.legacyToken,(s,i)=>ce.validateAnyPairToken(s,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(t.method==="POST"&&n.pathname==="/upload"){let s={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/heic":".heic","image/heif":".heif"},i=(t.headers["content-type"]??"").split(";")[0].trim(),o=s[i];if(!o){N(e,400,{error:"Unsupported content type"});return}let a=10*1024*1024,l=[],c=0;for await(let u of t){let d=Buffer.isBuffer(u)?u:Buffer.from(u);if(c+=d.length,c>a){e.writeHead(413),e.end("File too large");return}l.push(d)}try{await(0,re.mkdir)(zs,{recursive:!0});let u=`${Date.now()}_${(0,id.randomBytes)(8).toString("hex")}${o}`,d=(0,In.join)(zs,u);await(0,re.writeFile)(d,Buffer.concat(l)),q.info({filePath:d,size:c},"file uploaded"),N(e,200,{path:d})}catch(u){q.error({error:String(u)},"upload failed"),N(e,500,{error:"Upload failed"})}return}if(n.pathname==="/file"){let s=n.searchParams.get("path"),i=n.searchParams.get("cwd")||void 0;if(!s){e.writeHead(400),e.end("Missing path parameter");return}try{let o=Ti(s,i);if(!(await(0,re.stat)(o)).isFile()){e.writeHead(404),e.end("Not a file");return}let l=Wy(o),c=await(0,re.readFile)(o);e.writeHead(200,{"Content-Type":l,"Content-Length":c.length}),e.end(c)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${wt}`)}),le=new ns.default({server:An});An.on("connection",t=>{Lr.add(t),t.on("close",()=>{Lr.delete(t)})});le.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${S.port}`).searchParams.get("token");if(r&&Er(r,S.legacyToken))De.set(t,{authMode:"query_token"}),w.increment("ws.auth.success",{mode:"query_token"}),J.addGlobalClient(t),J.prewarmCaches();else if(r){let s=ce.validateAnyPairToken(r);if(s)De.set(t,{authMode:"query_token",deviceId:s.deviceId}),w.increment("ws.auth.success",{mode:"query_token"}),J.addGlobalClient(t),J.prewarmCaches();else{w.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}}bn.info({clients:le.clients.size},"client connected"),w.increment("ws.connect"),w.gauge("ws.clients",le.clients.size),I.emit("ws.connect",{clients:le.clients.size,authMode:De.get(t)?.authMode??"pending",deviceId:De.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(nd(s));if(!i||typeof i.action!="string"){t.send(JSON.stringify({type:"error",sessionId:"",message:'Invalid message: missing or non-string "action" field'}));return}if(i.action==="ping"){t.send(JSON.stringify({type:"pong"}));return}let o=i;if(!De.has(t)){if(o.action==="auth.hello"){let a=(()=>{if(Er(o.pairToken,S.legacyToken))return{deviceId:o.deviceId};if(o.deviceId&&o.daemonId===D.daemonId&&ce.validatePairToken(o.deviceId,o.pairToken))return{deviceId:o.deviceId};if(!o.daemonId||o.daemonId===D.daemonId){let l=ce.validateAnyPairToken(o.pairToken);if(l)return{deviceId:l.deviceId}}return null})();if(a){De.set(t,{authMode:"auth_hello",deviceId:a.deviceId}),w.increment("ws.auth.success",{mode:"auth_hello"}),J.addGlobalClient(t),J.prewarmCaches(),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:D.daemonId,displayName:D.displayName}}));return}w.increment("ws.auth.failure",{mode:"auth_hello"}),t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:"auth_failed"})),t.close(4001,"Unauthorized");return}w.increment("ws.auth.failure",{mode:"missing"}),t.send(JSON.stringify({type:"error",sessionId:"",message:"Authentication required"})),t.close(4001,"Unauthorized");return}if(o.action==="log.report"){for(let a of o.entries)I.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?q.error:a.level==="warn"?q.warn:q.info).call(q,{event:a.event,...a.data},`[app] ${a.event}`);t.send(JSON.stringify({type:"response",id:o.id,ok:!0}));return}if(o.action==="dirs.list"){try{let a=await Vy(o.path,o.cwd);t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:a}))}catch(a){t.send(JSON.stringify({type:"response",id:o.id,ok:!1,error:String(a)}))}return}if(i.action==="push.register"){let a=De.get(t);Ei(i,{deviceId:a?.deviceId,registerToken:xi,unregisterToken:Ci,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=De.get(t);Ei(i,{deviceId:a?.deviceId,registerToken:xi,unregisterToken:Ci,respond:l=>t.send(JSON.stringify(l))});return}await J.handle(t,o)}catch(i){bn.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{bn.info({clients:le.clients.size,code:s},"client disconnected"),w.increment("ws.disconnect"),w.increment("ws.disconnect.code",{code:String(s)}),w.gauge("ws.clients",le.clients.size),I.emit("ws.disconnect",{clients:le.clients.size,code:s}),J.removeClient(t)}),t.on("error",s=>{bn.error({error:s.message},"websocket error")})});function Hi(){for(let t of Lr)try{t.destroy()}catch{}Lr.clear()}function cd(){let t=mc({auditPath:St,stdoutLogPath:tr,stderrLogPath:nr,auditMaxBytes:S.auditMaxBytes,logMaxBytes:S.daemonLogMaxBytes});t.trimmedFiles>0&&q.info({trimmedFiles:t.trimmedFiles,reclaimedBytes:t.reclaimedBytes,files:t.files.filter(e=>e.trimmed).map(e=>({path:e.path,beforeBytes:e.beforeBytes,afterBytes:e.afterBytes}))},"trimmed vibelet storage")}function $y(){Ot||(Ot=setInterval(cd,S.storageHousekeepingIntervalMs),Ot.unref())}function zy(){Ot&&(clearInterval(Ot),Ot=null)}function tt(t,e=0){if(!rd){rd=!0,q.info({reason:t,exitCode:e},"shutting down"),I.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-ad)/1e3)}),w.stopPeriodicLog(),zy(),At.stop().catch(()=>{}),J.shutdown();for(let n of le.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}le.close(n=>{n&&q.error({error:String(n)},"websocket close error")}),An.close(n=>{if(n){q.error({error:String(n)},"http close error"),Hi(),process.exit(1);return}Hi(),process.exit(e)}),setTimeout(()=>{q.error("force exiting after shutdown timeout"),Hi(),process.exit(e||1)},3e3).unref()}}le.on("error",t=>{bn.error({error:t.message},"wss error")});An.on("error",t=>{if(t.code==="EADDRINUSE"){let e=Uu(S.port).filter(n=>n.pid!==process.pid);q.error({port:S.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else q.error({error:String(t)},"server error");tt(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>tt("SIGINT"));process.once("SIGTERM",()=>tt("SIGTERM"));process.once("SIGHUP",()=>tt("SIGHUP"));process.once("SIGTTIN",()=>tt("SIGTTIN"));process.once("SIGTSTP",()=>tt("SIGTSTP"));process.on("uncaughtException",t=>{q.error({error:String(t),stack:t.stack},"uncaughtException"),I.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{q.error({reason:String(t)},"unhandledRejection"),I.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});An.listen(S.port,async()=>{cd(),I.emit("daemon.start",{port:S.port}),w.startPeriodicLog(),$y(),nu(),At.start().catch(r=>{q.warn({error:String(r)},"session activity watcher failed to start")});let t=wn();q.info({port:S.port,pairingPort:t.port,daemonId:D.daemonId,displayName:D.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts,claudePath:S.claudePath,codexPath:S.codexPath,auditMaxBytes:S.auditMaxBytes,daemonLogMaxBytes:S.daemonLogMaxBytes,storageHousekeepingIntervalMs:S.storageHousekeepingIntervalMs,turnStallTimeoutMs:S.turnStallTimeoutMs},"daemon started");let e=ce.openWindow(ld(),S.pairReusable),n={type:"vibelet-pair",daemonId:D.daemonId,displayName:D.displayName,canonicalHost:t.canonicalHost,fallbackHosts:t.fallbackHosts.length>0?t.fallbackHosts:void 0,port:t.port,connections:t.connections,pairNonce:e.pairNonce,expiresAt:e.expiresAt};_t(`
111
110
  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
112
- \u2551 Vibelet Daemon v${an} \u2551
111
+ \u2551 Vibelet Daemon v${wt} \u2551
113
112
  \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563
114
113
  \u2551 Port: ${String(n.port).padEnd(28)}\u2551
115
- \u2551 ID: ${oe.daemonId.slice(0,28).padEnd(28)}\u2551
114
+ \u2551 ID: ${D.daemonId.slice(0,28).padEnd(28)}\u2551
116
115
  \u2551 Host: ${n.canonicalHost.slice(0,28).padEnd(28)}\u2551
117
116
  \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
118
117
 
@@ -120,6 +119,6 @@ Pair with: npx @vibelet/cli or npx vibelet
120
119
  Host: ${n.canonicalHost}
121
120
  Fallbacks: ${n.fallbackHosts?.join(", ")||"(none)"}
122
121
 
123
- Claude: ${C.claudePath}
124
- Codex: ${C.codexPath}
125
- `);try{await gE(n)}catch{}});
122
+ Claude: ${S.claudePath}
123
+ Codex: ${S.codexPath}
124
+ `);try{await qy(n)}catch{}});