vibelet 0.1.5 → 0.1.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.
Files changed (2) hide show
  1. package/dist/index.cjs +43 -43
  2. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -1,28 +1,28 @@
1
- "use strict";var ou=Object.create;var ai=Object.defineProperty;var au=Object.getOwnPropertyDescriptor;var lu=Object.getOwnPropertyNames;var cu=Object.getPrototypeOf,uu=Object.prototype.hasOwnProperty;var m=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var du=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lu(e))!uu.call(t,s)&&s!==r&&ai(t,s,{get:()=>e[s],enumerable:!(n=au(e,s))||n.enumerable});return t};var Ve=(t,e,r)=>(r=t!=null?ou(cu(t)):{},du(e||!t||!t.__esModule?ai(r,"default",{value:t,enumerable:!0}):r,t));var ue=m((sm,ui)=>{"use strict";var li=["nodebuffer","arraybuffer","fragments"],ci=typeof Blob<"u";ci&&li.push("blob");ui.exports={BINARY_TYPES:li,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ci,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var kt=m((im,ur)=>{"use strict";var{EMPTY_BUFFER:fu}=ue(),hn=Buffer[Symbol.species];function hu(t,e){if(t.length===0)return fu;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let s=0;s<t.length;s++){let i=t[s];r.set(i,n),n+=i.length}return n<e?new hn(r.buffer,r.byteOffset,n):r}function di(t,e,r,n,s){for(let i=0;i<s;i++)r[n+i]=t[i]^e[i&3]}function fi(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function pu(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function pn(t){if(pn.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new hn(t):ArrayBuffer.isView(t)?e=new hn(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),pn.readOnly=!1),e}ur.exports={concat:hu,mask:di,toArrayBuffer:pu,toBuffer:pn,unmask:fi};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");ur.exports.mask=function(e,r,n,s,i){i<48?di(e,r,n,s,i):t.mask(e,r,n,s,i)},ur.exports.unmask=function(e,r){e.length<32?fi(e,r):t.unmask(e,r)}}catch{}});var gi=m((om,pi)=>{"use strict";var hi=Symbol("kDone"),gn=Symbol("kRun"),mn=class{constructor(e){this[hi]=()=>{this.pending--,this[gn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[gn]()}[gn](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[hi])}}};pi.exports=mn});var At=m((am,_i)=>{"use strict";var Et=require("zlib"),mi=kt(),gu=gi(),{kStatusCode:yi}=ue(),mu=Buffer[Symbol.species],yu=Buffer.from([0,0,255,255]),fr=Symbol("permessage-deflate"),de=Symbol("total-length"),Ye=Symbol("callback"),ye=Symbol("buffers"),Je=Symbol("error"),dr,yn=class{constructor(e,r,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!r,this._deflate=null,this._inflate=null,this.params=null,!dr){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;dr=new gu(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[Ye];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(s=>!(r.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>s.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let s=r[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="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 "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=s})}),e}decompress(e,r,n){dr.add(s=>{this._decompress(e,r,(i,o)=>{s(),n(i,o)})})}compress(e,r,n){dr.add(s=>{this._compress(e,r,(i,o)=>{s(),n(i,o)})})}_decompress(e,r,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Et.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Et.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[fr]=this,this._inflate[de]=0,this._inflate[ye]=[],this._inflate.on("error",_u),this._inflate.on("data",Si)}this._inflate[Ye]=n,this._inflate.write(e),r&&this._inflate.write(yu),this._inflate.flush(()=>{let i=this._inflate[Je];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=mi.concat(this._inflate[ye],this._inflate[de]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[de]=0,this._inflate[ye]=[],r&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,r,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Et.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Et.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[de]=0,this._deflate[ye]=[],this._deflate.on("data",Su)}this._deflate[Ye]=n,this._deflate.write(e),this._deflate.flush(Et.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=mi.concat(this._deflate[ye],this._deflate[de]);r&&(i=new mu(i.buffer,i.byteOffset,i.length-4)),this._deflate[Ye]=null,this._deflate[de]=0,this._deflate[ye]=[],r&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};_i.exports=yn;function Su(t){this[ye].push(t),this[de]+=t.length}function Si(t){if(this[de]+=t.length,this[fr]._maxPayload<1||this[de]<=this[fr]._maxPayload){this[ye].push(t);return}this[Je]=new RangeError("Max payload size exceeded"),this[Je].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Je][yi]=1009,this.removeListener("data",Si),this.reset()}function _u(t){if(this[fr]._inflate=null,this[Je]){this[Ye](this[Je]);return}t[yi]=1007,this[Ye](t)}});var Ke=m((lm,hr)=>{"use strict";var{isUtf8:vi}=require("buffer"),{hasBlob:vu}=ue(),wu=[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 bu(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Sn(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function Iu(t){return vu&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}hr.exports={isBlob:Iu,isValidStatusCode:bu,isValidUTF8:Sn,tokenChars:wu};if(vi)hr.exports.isValidUTF8=function(t){return t.length<24?Sn(t):vi(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");hr.exports.isValidUTF8=function(e){return e.length<32?Sn(e):t(e)}}catch{}});var In=m((cm,Ei)=>{"use strict";var{Writable:xu}=require("stream"),wi=At(),{BINARY_TYPES:Tu,EMPTY_BUFFER:bi,kStatusCode:ku,kWebSocket:Eu}=ue(),{concat:_n,toArrayBuffer:Au,unmask:Cu}=kt(),{isValidStatusCode:Pu,isValidUTF8:Ii}=Ke(),pr=Buffer[Symbol.species],J=0,xi=1,Ti=2,ki=3,vn=4,wn=5,gr=6,bn=class extends xu{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Tu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Eu]=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=J}_write(e,r,n){if(this._opcode===8&&this._state==J)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new pr(n.buffer,n.byteOffset+e,n.length-e),new pr(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=r.length-e;e>=n.length?r.set(this._buffers.shift(),s):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new pr(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case J:this.getInfo(e);break;case xi:this.getPayloadLength16(e);break;case Ti:this.getPayloadLength64(e);break;case ki:this.getMask();break;case vn:this.getData(e);break;case wn:case gr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(r[0]&64)===64;if(n&&!this._extensions[wi.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){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=n}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(n){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=(r[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=xi:this._payloadLength===127?this._state=Ti:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>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=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=ki:this._state=vn}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=vn}getData(e){let r=bi;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Cu(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=wn,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[wi.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return r(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");r(o);return}this._fragments.push(i)}this.dataMessage(r),this._state===J&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=J;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=_n(n,r):this._binaryType==="arraybuffer"?s=Au(_n(n,r)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=J):(this._state=gr,setImmediate(()=>{this.emit("message",s,!0),this._state=J,this.startLoop(e)}))}else{let s=_n(n,r);if(!this._skipUTF8Validation&&!Ii(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===wn||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=J):(this._state=gr,setImmediate(()=>{this.emit("message",s,!1),this._state=J,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,bi),this.end();else{let n=e.readUInt16BE(0);if(!Pu(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(i);return}let s=new pr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ii(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=J;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=J):(this._state=gr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=J,this.startLoop(r)}))}createError(e,r,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(o,this.createError),o.code=i,o[ku]=s,o}};Ei.exports=bn});var kn=m((dm,Pi)=>{"use strict";var{Duplex:um}=require("stream"),{randomFillSync:Ru}=require("crypto"),Ai=At(),{EMPTY_BUFFER:Lu,kWebSocket:Mu,NOOP:Nu}=ue(),{isBlob:Xe,isValidStatusCode:Ou}=Ke(),{mask:Ci,toBuffer:Le}=kt(),K=Symbol("kByteLength"),Bu=Buffer.alloc(4),mr=8*1024,Me,Ze=mr,te=0,Du=1,Hu=2,xn=class t{constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=te,this.onerror=Nu,this[Mu]=void 0}static frame(e,r){let n,s=!1,i=2,o=!1;r.mask&&(n=r.maskBuffer||Bu,r.generateMask?r.generateMask(n):(Ze===mr&&(Me===void 0&&(Me=Buffer.alloc(mr)),Ru(Me,0,mr),Ze=0),n[0]=Me[Ze++],n[1]=Me[Ze++],n[2]=Me[Ze++],n[3]=Me[Ze++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!r.mask||o)&&r[K]!==void 0?a=r[K]:(e=Buffer.from(e),a=e.length):(a=e.length,s=r.mask&&r.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]=r.fin?r.opcode|128:r.opcode,r.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)),r.mask?(c[1]|=128,c[i-4]=n[0],c[i-3]=n[1],c[i-2]=n[2],c[i-1]=n[3],o?[c,e]:s?(Ci(e,n,c,i,a),[c]):(Ci(e,n,e,0,a),[c,e])):[c,e]}close(e,r,n,s){let i;if(e===void 0)i=Lu;else{if(typeof e!="number"||!Ou(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);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 r=="string"?i.write(r,2):i.set(r,2)}}let o={[K]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==te?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(t.frame(i,o),s)}ping(e,r,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Xe(e)?(s=e.size,i=!1):(e=Le(e),s=e.length,i=Le.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[K]:s,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Xe(e)?this._state!==te?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==te?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}pong(e,r,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Xe(e)?(s=e.size,i=!1):(e=Le(e),s=e.length,i=Le.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[K]:s,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Xe(e)?this._state!==te?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==te?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}send(e,r,n){let s=this._extensions[Ai.extensionName],i=r.binary?2:1,o=r.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):Xe(e)?(a=e.size,l=!1):(e=Le(e),a=e.length,l=Le.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),r.fin&&(this._firstFragment=!0);let c={[K]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};Xe(e)?this._state!==te?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):this._state!==te?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(e,r,n,s){this._bufferedBytes+=n[K],this._state=Hu,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Tn,this,a,s);return}this._bufferedBytes-=n[K];let o=Le(i);r?this.dispatch(o,r,n,s):(this._state=te,this.sendFrame(t.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(Fu,this,i,s)})}dispatch(e,r,n,s){if(!r){this.sendFrame(t.frame(e,n),s);return}let i=this._extensions[Ai.extensionName];this._bufferedBytes+=n[K],this._state=Du,i.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Tn(this,l,s);return}this._bufferedBytes-=n[K],this._state=te,n.readOnly=!1,this.sendFrame(t.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===te&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][K],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][K],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};Pi.exports=xn;function Tn(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let s=t._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function Fu(t,e,r){Tn(t,e,r),t.onerror(e)}});var Fi=m((fm,Hi)=>{"use strict";var{kForOnEventAttribute:Ct,kListener:En}=ue(),Ri=Symbol("kCode"),Li=Symbol("kData"),Mi=Symbol("kError"),Ni=Symbol("kMessage"),Oi=Symbol("kReason"),Qe=Symbol("kTarget"),Bi=Symbol("kType"),Di=Symbol("kWasClean"),fe=class{constructor(e){this[Qe]=null,this[Bi]=e}get target(){return this[Qe]}get type(){return this[Bi]}};Object.defineProperty(fe.prototype,"target",{enumerable:!0});Object.defineProperty(fe.prototype,"type",{enumerable:!0});var Ne=class extends fe{constructor(e,r={}){super(e),this[Ri]=r.code===void 0?0:r.code,this[Oi]=r.reason===void 0?"":r.reason,this[Di]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Ri]}get reason(){return this[Oi]}get wasClean(){return this[Di]}};Object.defineProperty(Ne.prototype,"code",{enumerable:!0});Object.defineProperty(Ne.prototype,"reason",{enumerable:!0});Object.defineProperty(Ne.prototype,"wasClean",{enumerable:!0});var et=class extends fe{constructor(e,r={}){super(e),this[Mi]=r.error===void 0?null:r.error,this[Ni]=r.message===void 0?"":r.message}get error(){return this[Mi]}get message(){return this[Ni]}};Object.defineProperty(et.prototype,"error",{enumerable:!0});Object.defineProperty(et.prototype,"message",{enumerable:!0});var Pt=class extends fe{constructor(e,r={}){super(e),this[Li]=r.data===void 0?null:r.data}get data(){return this[Li]}};Object.defineProperty(Pt.prototype,"data",{enumerable:!0});var Uu={addEventListener(t,e,r={}){for(let s of this.listeners(t))if(!r[Ct]&&s[En]===e&&!s[Ct])return;let n;if(t==="message")n=function(i,o){let a=new Pt("message",{data:o?i:i.toString()});a[Qe]=this,yr(e,this,a)};else if(t==="close")n=function(i,o){let a=new Ne("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Qe]=this,yr(e,this,a)};else if(t==="error")n=function(i){let o=new et("error",{error:i,message:i.message});o[Qe]=this,yr(e,this,o)};else if(t==="open")n=function(){let i=new fe("open");i[Qe]=this,yr(e,this,i)};else return;n[Ct]=!!r[Ct],n[En]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[En]===e&&!r[Ct]){this.removeListener(t,r);break}}};Hi.exports={CloseEvent:Ne,ErrorEvent:et,Event:fe,EventTarget:Uu,MessageEvent:Pt};function yr(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var An=m((hm,Ui)=>{"use strict";var{tokenChars:Rt}=Ke();function oe(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function qu(t){let e=Object.create(null),r=Object.create(null),n=!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&&Rt[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?(oe(e,h,r),r=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&&Rt[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),oe(r,t.slice(l,u),!0),c===44&&(oe(e,o,r),r=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(Rt[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:n||(n=!0),s=!1}else if(i)if(Rt[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&&Rt[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);n&&(h=h.replace(/\\/g,""),n=!1),oe(r,a,h),c===44&&(oe(e,o,r),r=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?oe(e,f,r):(a===void 0?oe(r,f,!0):n?oe(r,a,f.replace(/\\/g,"")):oe(r,a,f),oe(e,o,r)),e}function Wu(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ui.exports={format:Wu,parse:qu}});var wr=m((mm,Zi)=>{"use strict";var ju=require("events"),Gu=require("https"),zu=require("http"),ji=require("net"),$u=require("tls"),{randomBytes:Vu,createHash:Yu}=require("crypto"),{Duplex:pm,Readable:gm}=require("stream"),{URL:Cn}=require("url"),Se=At(),Ju=In(),Ku=kn(),{isBlob:Xu}=Ke(),{BINARY_TYPES:qi,CLOSE_TIMEOUT:Zu,EMPTY_BUFFER:Sr,GUID:Qu,kForOnEventAttribute:Pn,kListener:ed,kStatusCode:td,kWebSocket:N,NOOP:Gi}=ue(),{EventTarget:{addEventListener:rd,removeEventListener:nd}}=Fi(),{format:sd,parse:id}=An(),{toBuffer:od}=kt(),zi=Symbol("kAborted"),Rn=[8,13],he=["CONNECTING","OPEN","CLOSING","CLOSED"],ad=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,T=class t extends ju{constructor(e,r,n){super(),this._binaryType=qi[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Sr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),$i(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){qi.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let s=new Ju({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new Ku(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[N]=this,i[N]=this,e[N]=this,s.on("conclude",ud),s.on("drain",dd),s.on("error",fd),s.on("message",hd),s.on("ping",pd),s.on("pong",gd),i.onerror=md,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Ji),e.on("data",vr),e.on("end",Ki),e.on("error",Xi),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[Se.extensionName]&&this._extensions[Se.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){$(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Yi(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ln(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Sr,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ln(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Sr,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ln(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Se.extensionName]||(s.compress=!1),this._sender.send(e||Sr,s,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){$(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(T,"CONNECTING",{enumerable:!0,value:he.indexOf("CONNECTING")});Object.defineProperty(T.prototype,"CONNECTING",{enumerable:!0,value:he.indexOf("CONNECTING")});Object.defineProperty(T,"OPEN",{enumerable:!0,value:he.indexOf("OPEN")});Object.defineProperty(T.prototype,"OPEN",{enumerable:!0,value:he.indexOf("OPEN")});Object.defineProperty(T,"CLOSING",{enumerable:!0,value:he.indexOf("CLOSING")});Object.defineProperty(T.prototype,"CLOSING",{enumerable:!0,value:he.indexOf("CLOSING")});Object.defineProperty(T,"CLOSED",{enumerable:!0,value:he.indexOf("CLOSED")});Object.defineProperty(T.prototype,"CLOSED",{enumerable:!0,value:he.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(T.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(T.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Pn])return e[ed];return null},set(e){for(let r of this.listeners(t))if(r[Pn]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Pn]:!0})}})});T.prototype.addEventListener=rd;T.prototype.removeEventListener=nd;Zi.exports=T;function $i(t,e,r,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Zu,protocolVersion:Rn[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,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,!Rn.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Rn.join(", ")})`);let i;if(e instanceof Cn)i=e;else try{i=new Cn(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 g=new SyntaxError(l);if(t._redirects===0)throw g;_r(t,g);return}let c=o?443:80,u=Vu(16).toString("base64"),d=o?Gu.request:zu.request,f=new Set,h;if(s.createConnection=s.createConnection||(o?cd:ld),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 Se(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=sd({[Se.extensionName]:h.offer()})),r.length){for(let g of r){if(typeof g!="string"||!ad.test(g)||f.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(g)}s.headers["Sec-WebSocket-Protocol"]=r.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 g=s.path.split(":");s.socketPath=g[0],s.path=g[1]}let p;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let g=n&&n.headers;if(n={...n,headers:{}},g)for(let[y,S]of Object.entries(g))n.headers[y.toLowerCase()]=S}else if(t.listenerCount("redirect")===0){let g=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!g||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,g||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=t._req=d(s),t._redirects&&t.emit("redirect",t.url,p)}else p=t._req=d(s);s.timeout&&p.on("timeout",()=>{$(t,p,"Opening handshake has timed out")}),p.on("error",g=>{p===null||p[zi]||(p=t._req=null,_r(t,g))}),p.on("response",g=>{let y=g.headers.location,S=g.statusCode;if(y&&s.followRedirects&&S>=300&&S<400){if(++t._redirects>s.maxRedirects){$(t,p,"Maximum redirects exceeded");return}p.abort();let U;try{U=new Cn(y,e)}catch{let E=new SyntaxError(`Invalid URL: ${y}`);_r(t,E);return}$i(t,U,r,n)}else t.emit("unexpected-response",p,g)||$(t,p,`Unexpected server response: ${g.statusCode}`)}),p.on("upgrade",(g,y,S)=>{if(t.emit("upgrade",g),t.readyState!==T.CONNECTING)return;p=t._req=null;let U=g.headers.upgrade;if(U===void 0||U.toLowerCase()!=="websocket"){$(t,y,"Invalid Upgrade header");return}let se=Yu("sha1").update(u+Qu).digest("base64");if(g.headers["sec-websocket-accept"]!==se){$(t,y,"Invalid Sec-WebSocket-Accept header");return}let E=g.headers["sec-websocket-protocol"],M;if(E!==void 0?f.size?f.has(E)||(M="Server sent an invalid subprotocol"):M="Server sent a subprotocol but none was requested":f.size&&(M="Server sent no subprotocol"),M){$(t,y,M);return}E&&(t._protocol=E);let Y=g.headers["sec-websocket-extensions"];if(Y!==void 0){if(!h){$(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ie;try{ie=id(Y)}catch{$(t,y,"Invalid Sec-WebSocket-Extensions header");return}let $e=Object.keys(ie);if($e.length!==1||$e[0]!==Se.extensionName){$(t,y,"Server indicated an extension that was not requested");return}try{h.accept(ie[Se.extensionName])}catch{$(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Se.extensionName]=h}t.setSocket(y,S,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(p,t):p.end()}function _r(t,e){t._readyState=T.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function ld(t){return t.path=t.socketPath,ji.connect(t)}function cd(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ji.isIP(t.host)?"":t.host),$u.connect(t)}function $(t,e,r){t._readyState=T.CLOSING;let n=new Error(r);Error.captureStackTrace(n,$),e.setHeader?(e[zi]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(_r,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ln(t,e,r){if(e){let n=Xu(e)?e.size:od(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${he[t.readyState]})`);process.nextTick(r,n)}}function ud(t,e){let r=this[N];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[N]!==void 0&&(r._socket.removeListener("data",vr),process.nextTick(Vi,r._socket),t===1005?r.close():r.close(t,e))}function dd(){let t=this[N];t.isPaused||t._socket.resume()}function fd(t){let e=this[N];e._socket[N]!==void 0&&(e._socket.removeListener("data",vr),process.nextTick(Vi,e._socket),e.close(t[td])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Wi(){this[N].emitClose()}function hd(t,e){this[N].emit("message",t,e)}function pd(t){let e=this[N];e._autoPong&&e.pong(t,!this._isServer,Gi),e.emit("ping",t)}function gd(t){this[N].emit("pong",t)}function Vi(t){t.resume()}function md(t){let e=this[N];e.readyState!==T.CLOSED&&(e.readyState===T.OPEN&&(e._readyState=T.CLOSING,Yi(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Yi(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ji(){let t=this[N];if(this.removeListener("close",Ji),this.removeListener("data",vr),this.removeListener("end",Ki),t._readyState=T.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[N]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Wi),t._receiver.on("finish",Wi))}function vr(t){this[N]._receiver.write(t)||this.pause()}function Ki(){let t=this[N];t._readyState=T.CLOSING,t._receiver.end(),this.end()}function Xi(){let t=this[N];this.removeListener("error",Xi),this.on("error",Gi),t&&(t._readyState=T.CLOSING,this.destroy())}});var ro=m((Sm,to)=>{"use strict";var ym=wr(),{Duplex:yd}=require("stream");function Qi(t){t.emit("close")}function Sd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function eo(t){this.removeListener("error",eo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function _d(t,e){let r=!0,n=new yd({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(i,o){let a=!o&&n._readableState.objectMode?i.toString():i;n.push(a)||t.pause()}),t.once("error",function(i){n.destroyed||(r=!1,n.destroy(i))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(t.readyState===t.CLOSED){i(s),process.nextTick(Qi,n);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(Qi,n)}),r&&t.terminate()},n._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){n._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(s,i,o){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(s,i,o)});return}t.send(s,o)},n.on("end",Sd),n.on("error",eo),n}to.exports=_d});var so=m((_m,no)=>{"use strict";var{tokenChars:vd}=Ke();function wd(t){let e=new Set,r=-1,n=-1,s=0;for(s;s<t.length;s++){let o=t.charCodeAt(s);if(n===-1&&vd[o]===1)r===-1&&(r=s);else if(s!==0&&(o===32||o===9))n===-1&&r!==-1&&(n=s);else if(o===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=t.slice(r,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=t.slice(r,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}no.exports={parse:wd}});var fo=m((wm,uo)=>{"use strict";var bd=require("events"),br=require("http"),{Duplex:vm}=require("stream"),{createHash:Id}=require("crypto"),io=An(),Oe=At(),xd=so(),Td=wr(),{CLOSE_TIMEOUT:kd,GUID:Ed,kWebSocket:Ad}=ue(),Cd=/^[+/0-9A-Za-z]{22}==$/,oo=0,ao=1,co=2,Mn=class extends bd{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:kd,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Td,...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=br.createServer((n,s)=>{let i=br.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,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Pd(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=oo}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===co){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Lt,this);return}if(e&&this.once("close",e),this._state!==ao)if(this._state=ao,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(Lt,this):process.nextTick(Lt,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Lt(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,s){r.on("error",lo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Be(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Be(this,e,r,400,"Invalid Upgrade header");return}if(i===void 0||!Cd.test(i)){Be(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Be(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Mt(r,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=xd.parse(l)}catch{Be(this,e,r,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 Oe(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=io.parse(u);h[Oe.extensionName]&&(f.accept(h[Oe.extensionName]),d[Oe.extensionName]=f)}catch{Be(this,e,r,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,p,g,y)=>{if(!h)return Mt(r,p||401,g,y);this.completeUpgrade(d,i,c,e,r,n,s)});return}if(!this.options.verifyClient(f))return Mt(r,401)}this.completeUpgrade(d,i,c,e,r,n,s)}completeUpgrade(e,r,n,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Ad])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>oo)return Mt(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Id("sha1").update(r+Ed).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(n.size){let d=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[Oe.extensionName]){let d=e[Oe.extensionName].params,f=io.format({[Oe.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 au=Object.create;var ai=Object.defineProperty;var lu=Object.getOwnPropertyDescriptor;var cu=Object.getOwnPropertyNames;var uu=Object.getPrototypeOf,du=Object.prototype.hasOwnProperty;var y=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var fu=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of cu(e))!du.call(t,s)&&s!==n&&ai(t,s,{get:()=>e[s],enumerable:!(r=lu(e,s))||r.enumerable});return t};var Ve=(t,e,n)=>(n=t!=null?au(uu(t)):{},fu(e||!t||!t.__esModule?ai(n,"default",{value:t,enumerable:!0}):n,t));var de=y((cm,ui)=>{"use strict";var li=["nodebuffer","arraybuffer","fragments"],ci=typeof Blob<"u";ci&&li.push("blob");ui.exports={BINARY_TYPES:li,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ci,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var xt=y((um,dn)=>{"use strict";var{EMPTY_BUFFER:pu}=de(),pr=Buffer[Symbol.species];function hu(t,e){if(t.length===0)return pu;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 pr(n.buffer,n.byteOffset,r):n}function di(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function fi(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function gu(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function hr(t){if(hr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new pr(t):ArrayBuffer.isView(t)?e=new pr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),hr.readOnly=!1),e}dn.exports={concat:hu,mask:di,toArrayBuffer:gu,toBuffer:hr,unmask:fi};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");dn.exports.mask=function(e,n,r,s,i){i<48?di(e,n,r,s,i):t.mask(e,n,r,s,i)},dn.exports.unmask=function(e,n){e.length<32?fi(e,n):t.unmask(e,n)}}catch{}});var gi=y((dm,hi)=>{"use strict";var pi=Symbol("kDone"),gr=Symbol("kRun"),mr=class{constructor(e){this[pi]=()=>{this.pending--,this[gr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[gr]()}[gr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[pi])}}};hi.exports=mr});var Et=y((fm,vi)=>{"use strict";var Tt=require("zlib"),mi=xt(),mu=gi(),{kStatusCode:yi}=de(),yu=Buffer[Symbol.species],Su=Buffer.from([0,0,255,255]),pn=Symbol("permessage-deflate"),fe=Symbol("total-length"),Ye=Symbol("callback"),ye=Symbol("buffers"),Je=Symbol("error"),fn,yr=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,!fn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;fn=new mu(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[Ye];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){fn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){fn.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"?Tt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Tt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[pn]=this,this._inflate[fe]=0,this._inflate[ye]=[],this._inflate.on("error",_u),this._inflate.on("data",Si)}this._inflate[Ye]=r,this._inflate.write(e),n&&this._inflate.write(Su),this._inflate.flush(()=>{let i=this._inflate[Je];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=mi.concat(this._inflate[ye],this._inflate[fe]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[fe]=0,this._inflate[ye]=[],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"?Tt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Tt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[fe]=0,this._deflate[ye]=[],this._deflate.on("data",vu)}this._deflate[Ye]=r,this._deflate.write(e),this._deflate.flush(Tt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=mi.concat(this._deflate[ye],this._deflate[fe]);n&&(i=new yu(i.buffer,i.byteOffset,i.length-4)),this._deflate[Ye]=null,this._deflate[fe]=0,this._deflate[ye]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};vi.exports=yr;function vu(t){this[ye].push(t),this[fe]+=t.length}function Si(t){if(this[fe]+=t.length,this[pn]._maxPayload<1||this[fe]<=this[pn]._maxPayload){this[ye].push(t);return}this[Je]=new RangeError("Max payload size exceeded"),this[Je].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Je][yi]=1009,this.removeListener("data",Si),this.reset()}function _u(t){if(this[pn]._inflate=null,this[Je]){this[Ye](this[Je]);return}t[yi]=1007,this[Ye](t)}});var Ke=y((pm,hn)=>{"use strict";var{isUtf8:_i}=require("buffer"),{hasBlob:wu}=de(),bu=[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 Iu(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Sr(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 Au(t){return wu&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}hn.exports={isBlob:Au,isValidStatusCode:Iu,isValidUTF8:Sr,tokenChars:bu};if(_i)hn.exports.isValidUTF8=function(t){return t.length<24?Sr(t):_i(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");hn.exports.isValidUTF8=function(e){return e.length<32?Sr(e):t(e)}}catch{}});var Ir=y((hm,Ti)=>{"use strict";var{Writable:ku}=require("stream"),wi=Et(),{BINARY_TYPES:xu,EMPTY_BUFFER:bi,kStatusCode:Tu,kWebSocket:Eu}=de(),{concat:vr,toArrayBuffer:Cu,unmask:Pu}=xt(),{isValidStatusCode:Ru,isValidUTF8:Ii}=Ke(),gn=Buffer[Symbol.species],J=0,Ai=1,ki=2,xi=3,_r=4,wr=5,mn=6,br=class extends ku{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||xu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Eu]=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=J}_write(e,n,r){if(this._opcode===8&&this._state==J)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 gn(r.buffer,r.byteOffset+e,r.length-e),new gn(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 gn(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 J:this.getInfo(e);break;case Ai:this.getPayloadLength16(e);break;case ki:this.getPayloadLength64(e);break;case xi:this.getMask();break;case _r:this.getData(e);break;case wr:case mn: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[wi.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=Ai:this._payloadLength===127?this._state=ki: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=xi:this._state=_r}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=_r}getData(e){let n=bi;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&&Pu(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=wr,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[wi.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===J&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=J;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=vr(r,n):this._binaryType==="arraybuffer"?s=Cu(vr(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=J):(this._state=mn,setImmediate(()=>{this.emit("message",s,!0),this._state=J,this.startLoop(e)}))}else{let s=vr(r,n);if(!this._skipUTF8Validation&&!Ii(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===wr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=J):(this._state=mn,setImmediate(()=>{this.emit("message",s,!1),this._state=J,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,bi),this.end();else{let r=e.readUInt16BE(0);if(!Ru(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new gn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ii(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=J;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=J):(this._state=mn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=J,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[Tu]=s,o}};Ti.exports=br});var xr=y((mm,Pi)=>{"use strict";var{Duplex:gm}=require("stream"),{randomFillSync:Lu}=require("crypto"),Ei=Et(),{EMPTY_BUFFER:Mu,kWebSocket:Nu,NOOP:Ou}=de(),{isBlob:Xe,isValidStatusCode:Bu}=Ke(),{mask:Ci,toBuffer:Le}=xt(),K=Symbol("kByteLength"),Du=Buffer.alloc(4),yn=8*1024,Me,Ze=yn,te=0,Hu=1,Fu=2,Ar=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=te,this.onerror=Ou,this[Nu]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||Du,n.generateMask?n.generateMask(r):(Ze===yn&&(Me===void 0&&(Me=Buffer.alloc(yn)),Lu(Me,0,yn),Ze=0),r[0]=Me[Ze++],r[1]=Me[Ze++],r[2]=Me[Ze++],r[3]=Me[Ze++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[K]!==void 0?a=n[K]:(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?(Ci(e,r,c,i,a),[c]):(Ci(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=Mu;else{if(typeof e!="number"||!Bu(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={[K]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==te?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):Xe(e)?(s=e.size,i=!1):(e=Le(e),s=e.length,i=Le.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[K]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Xe(e)?this._state!==te?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==te?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):Xe(e)?(s=e.size,i=!1):(e=Le(e),s=e.length,i=Le.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[K]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Xe(e)?this._state!==te?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==te?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[Ei.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):Xe(e)?(a=e.size,l=!1):(e=Le(e),a=e.length,l=Le.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={[K]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};Xe(e)?this._state!==te?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==te?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[K],this._state=Fu,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(kr,this,a,s);return}this._bufferedBytes-=r[K];let o=Le(i);n?this.dispatch(o,n,r,s):(this._state=te,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Uu,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[Ei.extensionName];this._bufferedBytes+=r[K],this._state=Hu,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");kr(this,l,s);return}this._bufferedBytes-=r[K],this._state=te,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===te&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][K],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][K],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)}};Pi.exports=Ar;function kr(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 Uu(t,e,n){kr(t,e,n),t.onerror(e)}});var Fi=y((ym,Hi)=>{"use strict";var{kForOnEventAttribute:Ct,kListener:Tr}=de(),Ri=Symbol("kCode"),Li=Symbol("kData"),Mi=Symbol("kError"),Ni=Symbol("kMessage"),Oi=Symbol("kReason"),Qe=Symbol("kTarget"),Bi=Symbol("kType"),Di=Symbol("kWasClean"),pe=class{constructor(e){this[Qe]=null,this[Bi]=e}get target(){return this[Qe]}get type(){return this[Bi]}};Object.defineProperty(pe.prototype,"target",{enumerable:!0});Object.defineProperty(pe.prototype,"type",{enumerable:!0});var Ne=class extends pe{constructor(e,n={}){super(e),this[Ri]=n.code===void 0?0:n.code,this[Oi]=n.reason===void 0?"":n.reason,this[Di]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Ri]}get reason(){return this[Oi]}get wasClean(){return this[Di]}};Object.defineProperty(Ne.prototype,"code",{enumerable:!0});Object.defineProperty(Ne.prototype,"reason",{enumerable:!0});Object.defineProperty(Ne.prototype,"wasClean",{enumerable:!0});var et=class extends pe{constructor(e,n={}){super(e),this[Mi]=n.error===void 0?null:n.error,this[Ni]=n.message===void 0?"":n.message}get error(){return this[Mi]}get message(){return this[Ni]}};Object.defineProperty(et.prototype,"error",{enumerable:!0});Object.defineProperty(et.prototype,"message",{enumerable:!0});var Pt=class extends pe{constructor(e,n={}){super(e),this[Li]=n.data===void 0?null:n.data}get data(){return this[Li]}};Object.defineProperty(Pt.prototype,"data",{enumerable:!0});var qu={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Ct]&&s[Tr]===e&&!s[Ct])return;let r;if(t==="message")r=function(i,o){let a=new Pt("message",{data:o?i:i.toString()});a[Qe]=this,Sn(e,this,a)};else if(t==="close")r=function(i,o){let a=new Ne("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Qe]=this,Sn(e,this,a)};else if(t==="error")r=function(i){let o=new et("error",{error:i,message:i.message});o[Qe]=this,Sn(e,this,o)};else if(t==="open")r=function(){let i=new pe("open");i[Qe]=this,Sn(e,this,i)};else return;r[Ct]=!!n[Ct],r[Tr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Tr]===e&&!n[Ct]){this.removeListener(t,n);break}}};Hi.exports={CloseEvent:Ne,ErrorEvent:et,Event:pe,EventTarget:qu,MessageEvent:Pt};function Sn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Er=y((Sm,Ui)=>{"use strict";var{tokenChars:Rt}=Ke();function oe(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Wu(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&&Rt[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?(oe(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&&Rt[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),oe(n,t.slice(l,u),!0),c===44&&(oe(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(Rt[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:r||(r=!0),s=!1}else if(i)if(Rt[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&&Rt[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),oe(n,a,p),c===44&&(oe(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?oe(e,f,n):(a===void 0?oe(n,f,!0):r?oe(n,a,f.replace(/\\/g,"")):oe(n,a,f),oe(e,o,n)),e}function ju(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(", ")}Ui.exports={format:ju,parse:Wu}});var bn=y((wm,Zi)=>{"use strict";var Gu=require("events"),$u=require("https"),zu=require("http"),ji=require("net"),Vu=require("tls"),{randomBytes:Yu,createHash:Ju}=require("crypto"),{Duplex:vm,Readable:_m}=require("stream"),{URL:Cr}=require("url"),Se=Et(),Ku=Ir(),Xu=xr(),{isBlob:Zu}=Ke(),{BINARY_TYPES:qi,CLOSE_TIMEOUT:Qu,EMPTY_BUFFER:vn,GUID:ed,kForOnEventAttribute:Pr,kListener:td,kStatusCode:nd,kWebSocket:N,NOOP:Gi}=de(),{EventTarget:{addEventListener:rd,removeEventListener:sd}}=Fi(),{format:id,parse:od}=Er(),{toBuffer:ad}=xt(),$i=Symbol("kAborted"),Rr=[8,13],he=["CONNECTING","OPEN","CLOSING","CLOSED"],ld=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,k=class t extends Gu{constructor(e,n,r){super(),this._binaryType=qi[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=vn,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]),zi(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){qi.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 Ku({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Xu(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[N]=this,i[N]=this,e[N]=this,s.on("conclude",dd),s.on("drain",fd),s.on("error",pd),s.on("message",hd),s.on("ping",gd),s.on("pong",md),i.onerror=yd,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Ji),e.on("data",wn),e.on("end",Ki),e.on("error",Xi),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[Se.extensionName]&&this._extensions[Se.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){z(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())}),Yi(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){Lr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||vn,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){Lr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||vn,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){Lr(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Se.extensionName]||(s.compress=!1),this._sender.send(e||vn,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){z(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:he.indexOf("CONNECTING")});Object.defineProperty(k.prototype,"CONNECTING",{enumerable:!0,value:he.indexOf("CONNECTING")});Object.defineProperty(k,"OPEN",{enumerable:!0,value:he.indexOf("OPEN")});Object.defineProperty(k.prototype,"OPEN",{enumerable:!0,value:he.indexOf("OPEN")});Object.defineProperty(k,"CLOSING",{enumerable:!0,value:he.indexOf("CLOSING")});Object.defineProperty(k.prototype,"CLOSING",{enumerable:!0,value:he.indexOf("CLOSING")});Object.defineProperty(k,"CLOSED",{enumerable:!0,value:he.indexOf("CLOSED")});Object.defineProperty(k.prototype,"CLOSED",{enumerable:!0,value:he.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[Pr])return e[td];return null},set(e){for(let n of this.listeners(t))if(n[Pr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Pr]:!0})}})});k.prototype.addEventListener=rd;k.prototype.removeEventListener=sd;Zi.exports=k;function zi(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Qu,protocolVersion:Rr[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,!Rr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Rr.join(", ")})`);let i;if(e instanceof Cr)i=e;else try{i=new Cr(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 g=new SyntaxError(l);if(t._redirects===0)throw g;_n(t,g);return}let c=o?443:80,u=Yu(16).toString("base64"),d=o?$u.request:zu.request,f=new Set,p;if(s.createConnection=s.createConnection||(o?ud:cd),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 Se(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=id({[Se.extensionName]:p.offer()})),n.length){for(let g of n){if(typeof g!="string"||!ld.test(g)||f.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(g)}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 g=s.path.split(":");s.socketPath=g[0],s.path=g[1]}let h;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let g=r&&r.headers;if(r={...r,headers:{}},g)for(let[m,S]of Object.entries(g))r.headers[m.toLowerCase()]=S}else if(t.listenerCount("redirect")===0){let g=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!g||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,g||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),h=t._req=d(s),t._redirects&&t.emit("redirect",t.url,h)}else h=t._req=d(s);s.timeout&&h.on("timeout",()=>{z(t,h,"Opening handshake has timed out")}),h.on("error",g=>{h===null||h[$i]||(h=t._req=null,_n(t,g))}),h.on("response",g=>{let m=g.headers.location,S=g.statusCode;if(m&&s.followRedirects&&S>=300&&S<400){if(++t._redirects>s.maxRedirects){z(t,h,"Maximum redirects exceeded");return}h.abort();let U;try{U=new Cr(m,e)}catch{let T=new SyntaxError(`Invalid URL: ${m}`);_n(t,T);return}zi(t,U,n,r)}else t.emit("unexpected-response",h,g)||z(t,h,`Unexpected server response: ${g.statusCode}`)}),h.on("upgrade",(g,m,S)=>{if(t.emit("upgrade",g),t.readyState!==k.CONNECTING)return;h=t._req=null;let U=g.headers.upgrade;if(U===void 0||U.toLowerCase()!=="websocket"){z(t,m,"Invalid Upgrade header");return}let se=Ju("sha1").update(u+ed).digest("base64");if(g.headers["sec-websocket-accept"]!==se){z(t,m,"Invalid Sec-WebSocket-Accept header");return}let T=g.headers["sec-websocket-protocol"],M;if(T!==void 0?f.size?f.has(T)||(M="Server sent an invalid subprotocol"):M="Server sent a subprotocol but none was requested":f.size&&(M="Server sent no subprotocol"),M){z(t,m,M);return}T&&(t._protocol=T);let Y=g.headers["sec-websocket-extensions"];if(Y!==void 0){if(!p){z(t,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ie;try{ie=od(Y)}catch{z(t,m,"Invalid Sec-WebSocket-Extensions header");return}let ze=Object.keys(ie);if(ze.length!==1||ze[0]!==Se.extensionName){z(t,m,"Server indicated an extension that was not requested");return}try{p.accept(ie[Se.extensionName])}catch{z(t,m,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Se.extensionName]=p}t.setSocket(m,S,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(h,t):h.end()}function _n(t,e){t._readyState=k.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function cd(t){return t.path=t.socketPath,ji.connect(t)}function ud(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=ji.isIP(t.host)?"":t.host),Vu.connect(t)}function z(t,e,n){t._readyState=k.CLOSING;let r=new Error(n);Error.captureStackTrace(r,z),e.setHeader?(e[$i]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(_n,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Lr(t,e,n){if(e){let r=Zu(e)?e.size:ad(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${he[t.readyState]})`);process.nextTick(n,r)}}function dd(t,e){let n=this[N];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[N]!==void 0&&(n._socket.removeListener("data",wn),process.nextTick(Vi,n._socket),t===1005?n.close():n.close(t,e))}function fd(){let t=this[N];t.isPaused||t._socket.resume()}function pd(t){let e=this[N];e._socket[N]!==void 0&&(e._socket.removeListener("data",wn),process.nextTick(Vi,e._socket),e.close(t[nd])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Wi(){this[N].emitClose()}function hd(t,e){this[N].emit("message",t,e)}function gd(t){let e=this[N];e._autoPong&&e.pong(t,!this._isServer,Gi),e.emit("ping",t)}function md(t){this[N].emit("pong",t)}function Vi(t){t.resume()}function yd(t){let e=this[N];e.readyState!==k.CLOSED&&(e.readyState===k.OPEN&&(e._readyState=k.CLOSING,Yi(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Yi(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ji(){let t=this[N];if(this.removeListener("close",Ji),this.removeListener("data",wn),this.removeListener("end",Ki),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[N]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Wi),t._receiver.on("finish",Wi))}function wn(t){this[N]._receiver.write(t)||this.pause()}function Ki(){let t=this[N];t._readyState=k.CLOSING,t._receiver.end(),this.end()}function Xi(){let t=this[N];this.removeListener("error",Xi),this.on("error",Gi),t&&(t._readyState=k.CLOSING,this.destroy())}});var no=y((Im,to)=>{"use strict";var bm=bn(),{Duplex:Sd}=require("stream");function Qi(t){t.emit("close")}function vd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function eo(t){this.removeListener("error",eo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function _d(t,e){let n=!0,r=new Sd({...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(Qi,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(Qi,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",vd),r.on("error",eo),r}to.exports=_d});var so=y((Am,ro)=>{"use strict";var{tokenChars:wd}=Ke();function bd(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&&wd[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}ro.exports={parse:bd}});var fo=y((xm,uo)=>{"use strict";var Id=require("events"),In=require("http"),{Duplex:km}=require("stream"),{createHash:Ad}=require("crypto"),io=Er(),Oe=Et(),kd=so(),xd=bn(),{CLOSE_TIMEOUT:Td,GUID:Ed,kWebSocket:Cd}=de(),Pd=/^[+/0-9A-Za-z]{22}==$/,oo=0,ao=1,co=2,Mr=class extends Id{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Td,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:xd,...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=In.createServer((r,s)=>{let i=In.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=Rd(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=oo}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===co){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Lt,this);return}if(e&&this.once("close",e),this._state!==ao)if(this._state=ao,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(Lt,this):process.nextTick(Lt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Lt(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",lo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Be(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Be(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!Pd.test(i)){Be(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Be(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Mt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=kd.parse(l)}catch{Be(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 Oe(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=io.parse(u);p[Oe.extensionName]&&(f.accept(p[Oe.extensionName]),d[Oe.extensionName]=f)}catch{Be(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,h,g,m)=>{if(!p)return Mt(n,h||401,g,m);this.completeUpgrade(d,i,c,e,n,r,s)});return}if(!this.options.verifyClient(f))return Mt(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[Cd])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>oo)return Mt(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ad("sha1").update(n+Ed).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[Oe.extensionName]){let d=e[Oe.extensionName].params,f=io.format({[Oe.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",lo),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(Lt,this)})),a(u,s)}};uo.exports=Mn;function Pd(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function Lt(t){t._state=co,t.emit("close")}function lo(){this.destroy()}function Mt(t,e,r,n){r=r||br.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${br.STATUS_CODES[e]}\r
4
- `+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
3
+ `)),i.removeListener("error",lo),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(Lt,this)})),a(u,s)}};uo.exports=Mr;function Rd(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 Lt(t){t._state=co,t.emit("close")}function lo(){this.destroy()}function Mt(t,e,n,r){n=n||In.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} ${In.STATUS_CODES[e]}\r
4
+ `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
5
5
  `)+`\r
6
6
  \r
7
- `+r)}function Be(t,e,r,n,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Be),t.emit("wsClientError",o,r,e)}else Mt(r,n,s,i)}});var On=m((Im,ho)=>{ho.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var _e=m(De=>{var Bn,Od=[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];De.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};De.getSymbolTotalCodewords=function(e){return Od[e]};De.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};De.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Bn=e};De.isKanjiModeEnabled=function(){return typeof Bn<"u"};De.toSJIS=function(e){return Bn(e)}});var Ir=m(X=>{X.L={bit:1};X.M={bit:0};X.Q={bit:3};X.H={bit:2};function Bd(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return X.L;case"m":case"medium":return X.M;case"q":case"quartile":return X.Q;case"h":case"high":return X.H;default:throw new Error("Unknown EC Level: "+t)}}X.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};X.from=function(e,r){if(X.isValid(e))return e;try{return Bd(e)}catch{return r}}});var mo=m((km,go)=>{function po(){this.buffer=[],this.length=0}po.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};go.exports=po});var So=m((Em,yo)=>{function Nt(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)}Nt.prototype.set=function(t,e,r,n){let s=t*this.size+e;this.data[s]=r,n&&(this.reservedBit[s]=!0)};Nt.prototype.get=function(t,e){return this.data[t*this.size+e]};Nt.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};Nt.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};yo.exports=Nt});var _o=m(xr=>{var Dd=_e().getSymbolSize;xr.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=Dd(e),s=n===145?26:Math.ceil((n-13)/(2*r-2))*2,i=[n-7];for(let o=1;o<r-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};xr.getPositions=function(e){let r=[],n=xr.getRowColCoords(e),s=n.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||r.push([n[i],n[o]]);return r}});var bo=m(wo=>{var Hd=_e().getSymbolSize,vo=7;wo.getPositions=function(e){let r=Hd(e);return[[0,0],[r-vo,0],[0,r-vo]]}});var Io=m(x=>{x.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var He={N1:3,N2:3,N3:40,N4:10};x.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};x.from=function(e){return x.isValid(e)?parseInt(e,10):void 0};x.getPenaltyN1=function(e){let r=e.size,n=0,s=0,i=0,o=null,a=null;for(let l=0;l<r;l++){s=i=0,o=a=null;for(let c=0;c<r;c++){let u=e.get(l,c);u===o?s++:(s>=5&&(n+=He.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(n+=He.N1+(i-5)),a=u,i=1)}s>=5&&(n+=He.N1+(s-5)),i>=5&&(n+=He.N1+(i-5))}return n};x.getPenaltyN2=function(e){let r=e.size,n=0;for(let s=0;s<r-1;s++)for(let i=0;i<r-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)&&n++}return n*He.N2};x.getPenaltyN3=function(e){let r=e.size,n=0,s=0,i=0;for(let o=0;o<r;o++){s=i=0;for(let a=0;a<r;a++)s=s<<1&2047|e.get(o,a),a>=10&&(s===1488||s===93)&&n++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&n++}return n*He.N3};x.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let i=0;i<n;i++)r+=e.data[i];return Math.abs(Math.ceil(r*100/n/5)-10)*He.N4};function Fd(t,e,r){switch(t){case x.Patterns.PATTERN000:return(e+r)%2===0;case x.Patterns.PATTERN001:return e%2===0;case x.Patterns.PATTERN010:return r%3===0;case x.Patterns.PATTERN011:return(e+r)%3===0;case x.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2===0;case x.Patterns.PATTERN101:return e*r%2+e*r%3===0;case x.Patterns.PATTERN110:return(e*r%2+e*r%3)%2===0;case x.Patterns.PATTERN111:return(e*r%3+(e+r)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}x.applyMask=function(e,r){let n=r.size;for(let s=0;s<n;s++)for(let i=0;i<n;i++)r.isReserved(i,s)||r.xor(i,s,Fd(e,i,s))};x.getBestMask=function(e,r){let n=Object.keys(x.Patterns).length,s=0,i=1/0;for(let o=0;o<n;o++){r(o),x.applyMask(o,e);let a=x.getPenaltyN1(e)+x.getPenaltyN2(e)+x.getPenaltyN3(e)+x.getPenaltyN4(e);x.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var Hn=m(Dn=>{var ve=Ir(),Tr=[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],kr=[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];Dn.getBlocksCount=function(e,r){switch(r){case ve.L:return Tr[(e-1)*4+0];case ve.M:return Tr[(e-1)*4+1];case ve.Q:return Tr[(e-1)*4+2];case ve.H:return Tr[(e-1)*4+3];default:return}};Dn.getTotalCodewordsCount=function(e,r){switch(r){case ve.L:return kr[(e-1)*4+0];case ve.M:return kr[(e-1)*4+1];case ve.Q:return kr[(e-1)*4+2];case ve.H:return kr[(e-1)*4+3];default:return}}});var xo=m(Ar=>{var Ot=new Uint8Array(512),Er=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Ot[r]=e,Er[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Ot[r]=Ot[r-255]})();Ar.log=function(e){if(e<1)throw new Error("log("+e+")");return Er[e]};Ar.exp=function(e){return Ot[e]};Ar.mul=function(e,r){return e===0||r===0?0:Ot[Er[e]+Er[r]]}});var To=m(Bt=>{var Fn=xo();Bt.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<r.length;i++)n[s+i]^=Fn.mul(e[s],r[i]);return n};Bt.mod=function(e,r){let n=new Uint8Array(e);for(;n.length-r.length>=0;){let s=n[0];for(let o=0;o<r.length;o++)n[o]^=Fn.mul(r[o],s);let i=0;for(;i<n.length&&n[i]===0;)i++;n=n.slice(i)}return n};Bt.generateECPolynomial=function(e){let r=new Uint8Array([1]);for(let n=0;n<e;n++)r=Bt.mul(r,new Uint8Array([1,Fn.exp(n)]));return r}});var Ao=m((Nm,Eo)=>{var ko=To();function Un(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Un.prototype.initialize=function(e){this.degree=e,this.genPoly=ko.generateECPolynomial(this.degree)};Un.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let n=ko.mod(r,this.genPoly),s=this.degree-n.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(n,s),i}return n};Eo.exports=Un});var qn=m(Co=>{Co.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Wn=m(pe=>{var Po="[0-9]+",Ud="[A-Z $%*+\\-./:]+",Dt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Dt=Dt.replace(/u/g,"\\u");var qd="(?:(?![A-Z0-9 $%*+\\-./:]|"+Dt+`)(?:.|[\r
8
- ]))+`;pe.KANJI=new RegExp(Dt,"g");pe.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");pe.BYTE=new RegExp(qd,"g");pe.NUMERIC=new RegExp(Po,"g");pe.ALPHANUMERIC=new RegExp(Ud,"g");var Wd=new RegExp("^"+Dt+"$"),jd=new RegExp("^"+Po+"$"),Gd=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");pe.testKanji=function(e){return Wd.test(e)};pe.testNumeric=function(e){return jd.test(e)};pe.testAlphanumeric=function(e){return Gd.test(e)}});var we=m(P=>{var zd=qn(),jn=Wn();P.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};P.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};P.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};P.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};P.MIXED={bit:-1};P.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!zd.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};P.getBestModeForData=function(e){return jn.testNumeric(e)?P.NUMERIC:jn.testAlphanumeric(e)?P.ALPHANUMERIC:jn.testKanji(e)?P.KANJI:P.BYTE};P.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};P.isValid=function(e){return e&&e.bit&&e.ccBits};function $d(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return P.NUMERIC;case"alphanumeric":return P.ALPHANUMERIC;case"kanji":return P.KANJI;case"byte":return P.BYTE;default:throw new Error("Unknown mode: "+t)}}P.from=function(e,r){if(P.isValid(e))return e;try{return $d(e)}catch{return r}}});var Oo=m(Fe=>{var Cr=_e(),Vd=Hn(),Ro=Ir(),be=we(),Gn=qn(),Mo=7973,Lo=Cr.getBCHDigit(Mo);function Yd(t,e,r){for(let n=1;n<=40;n++)if(e<=Fe.getCapacity(n,r,t))return n}function No(t,e){return be.getCharCountIndicator(t,e)+4}function Jd(t,e){let r=0;return t.forEach(function(n){let s=No(n.mode,e);r+=s+n.getBitsLength()}),r}function Kd(t,e){for(let r=1;r<=40;r++)if(Jd(t,r)<=Fe.getCapacity(r,e,be.MIXED))return r}Fe.from=function(e,r){return Gn.isValid(e)?parseInt(e,10):r};Fe.getCapacity=function(e,r,n){if(!Gn.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=be.BYTE);let s=Cr.getSymbolTotalCodewords(e),i=Vd.getTotalCodewordsCount(e,r),o=(s-i)*8;if(n===be.MIXED)return o;let a=o-No(n,e);switch(n){case be.NUMERIC:return Math.floor(a/10*3);case be.ALPHANUMERIC:return Math.floor(a/11*2);case be.KANJI:return Math.floor(a/13);case be.BYTE:default:return Math.floor(a/8)}};Fe.getBestVersionForData=function(e,r){let n,s=Ro.from(r,Ro.M);if(Array.isArray(e)){if(e.length>1)return Kd(e,s);if(e.length===0)return 1;n=e[0]}else n=e;return Yd(n.mode,n.getLength(),s)};Fe.getEncodedBits=function(e){if(!Gn.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;Cr.getBCHDigit(r)-Lo>=0;)r^=Mo<<Cr.getBCHDigit(r)-Lo;return e<<12|r}});var Fo=m(Ho=>{var zn=_e(),Do=1335,Xd=21522,Bo=zn.getBCHDigit(Do);Ho.getEncodedBits=function(e,r){let n=e.bit<<3|r,s=n<<10;for(;zn.getBCHDigit(s)-Bo>=0;)s^=Do<<zn.getBCHDigit(s)-Bo;return(n<<10|s)^Xd}});var qo=m((Um,Uo)=>{var Zd=we();function tt(t){this.mode=Zd.NUMERIC,this.data=t.toString()}tt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};tt.prototype.getLength=function(){return this.data.length};tt.prototype.getBitsLength=function(){return tt.getBitsLength(this.data.length)};tt.prototype.write=function(e){let r,n,s;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),s=parseInt(n,10),e.put(s,10);let i=this.data.length-r;i>0&&(n=this.data.substr(r),s=parseInt(n,10),e.put(s,i*3+1))};Uo.exports=tt});var jo=m((qm,Wo)=>{var Qd=we(),$n=["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 rt(t){this.mode=Qd.ALPHANUMERIC,this.data=t}rt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};rt.prototype.getLength=function(){return this.data.length};rt.prototype.getBitsLength=function(){return rt.getBitsLength(this.data.length)};rt.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=$n.indexOf(this.data[r])*45;n+=$n.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put($n.indexOf(this.data[r]),6)};Wo.exports=rt});var zo=m((Wm,Go)=>{var ef=we();function nt(t){this.mode=ef.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}nt.getBitsLength=function(e){return e*8};nt.prototype.getLength=function(){return this.data.length};nt.prototype.getBitsLength=function(){return nt.getBitsLength(this.data.length)};nt.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};Go.exports=nt});var Vo=m((jm,$o)=>{var tf=we(),rf=_e();function st(t){this.mode=tf.KANJI,this.data=t}st.getBitsLength=function(e){return e*13};st.prototype.getLength=function(){return this.data.length};st.prototype.getBitsLength=function(){return st.getBitsLength(this.data.length)};st.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=rf.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
9
- Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};$o.exports=st});var Yo=m((Gm,Vn)=>{"use strict";var Ht={single_source_shortest_paths:function(t,e,r){var n={},s={};s[e]=0;var i=Ht.PriorityQueue.make();i.push(e,0);for(var o,a,l,c,u,d,f,h,p;!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],p=typeof s[l]>"u",(p||h>f)&&(s[l]=f,i.push(l,f),n[l]=a))}if(typeof r<"u"&&typeof s[r]>"u"){var g=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(g)}return n},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],n=e,s;n;)r.push(n),s=t[n],n=t[n];return r.reverse(),r},find_path:function(t,e,r){var n=Ht.single_source_shortest_paths(t,e,r);return Ht.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=Ht.PriorityQueue,r={},n;t=t||{};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof Vn<"u"&&(Vn.exports=Ht)});var ra=m(it=>{var I=we(),Xo=qo(),Zo=jo(),Qo=zo(),ea=Vo(),Ft=Wn(),Pr=_e(),nf=Yo();function Jo(t){return unescape(encodeURIComponent(t)).length}function Ut(t,e,r){let n=[],s;for(;(s=t.exec(r))!==null;)n.push({data:s[0],index:s.index,mode:e,length:s[0].length});return n}function ta(t){let e=Ut(Ft.NUMERIC,I.NUMERIC,t),r=Ut(Ft.ALPHANUMERIC,I.ALPHANUMERIC,t),n,s;return Pr.isKanjiModeEnabled()?(n=Ut(Ft.BYTE,I.BYTE,t),s=Ut(Ft.KANJI,I.KANJI,t)):(n=Ut(Ft.BYTE_KANJI,I.BYTE,t),s=[]),e.concat(r,n,s).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Yn(t,e){switch(e){case I.NUMERIC:return Xo.getBitsLength(t);case I.ALPHANUMERIC:return Zo.getBitsLength(t);case I.KANJI:return ea.getBitsLength(t);case I.BYTE:return Qo.getBitsLength(t)}}function sf(t){return t.reduce(function(e,r){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function of(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];switch(n.mode){case I.NUMERIC:e.push([n,{data:n.data,mode:I.ALPHANUMERIC,length:n.length},{data:n.data,mode:I.BYTE,length:n.length}]);break;case I.ALPHANUMERIC:e.push([n,{data:n.data,mode:I.BYTE,length:n.length}]);break;case I.KANJI:e.push([n,{data:n.data,mode:I.BYTE,length:Jo(n.data)}]);break;case I.BYTE:e.push([{data:n.data,mode:I.BYTE,length:Jo(n.data)}])}}return e}function af(t,e){let r={},n={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),r[u]={node:c,lastCount:0},n[u]={};for(let d=0;d<s.length;d++){let f=s[d];r[f]&&r[f].node.mode===c.mode?(n[f][u]=Yn(r[f].lastCount+c.length,c.mode)-Yn(r[f].lastCount,c.mode),r[f].lastCount+=c.length):(r[f]&&(r[f].lastCount=c.length),n[f][u]=Yn(c.length,c.mode)+4+I.getCharCountIndicator(c.mode,e))}}s=a}for(let i=0;i<s.length;i++)n[s[i]].end=0;return{map:n,table:r}}function Ko(t,e){let r,n=I.getBestModeForData(t);if(r=I.from(e,n),r!==I.BYTE&&r.bit<n.bit)throw new Error('"'+t+'" cannot be encoded with mode '+I.toString(r)+`.
10
- Suggested mode is: `+I.toString(n));switch(r===I.KANJI&&!Pr.isKanjiModeEnabled()&&(r=I.BYTE),r){case I.NUMERIC:return new Xo(t);case I.ALPHANUMERIC:return new Zo(t);case I.KANJI:return new ea(t);case I.BYTE:return new Qo(t)}}it.fromArray=function(e){return e.reduce(function(r,n){return typeof n=="string"?r.push(Ko(n,null)):n.data&&r.push(Ko(n.data,n.mode)),r},[])};it.fromString=function(e,r){let n=ta(e,Pr.isKanjiModeEnabled()),s=of(n),i=af(s,r),o=nf.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return it.fromArray(sf(a))};it.rawSplit=function(e){return it.fromArray(ta(e,Pr.isKanjiModeEnabled()))}});var es=m(na=>{var Lr=_e(),Jn=Ir(),lf=mo(),cf=So(),uf=_o(),df=bo(),Zn=Io(),Qn=Hn(),ff=Ao(),Rr=Oo(),hf=Fo(),pf=we(),Kn=ra();function gf(t,e){let r=t.size,n=df.getPositions(e);for(let s=0;s<n.length;s++){let i=n[s][0],o=n[s][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||r<=i+a))for(let l=-1;l<=7;l++)o+l<=-1||r<=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 mf(t){let e=t.size;for(let r=8;r<e-8;r++){let n=r%2===0;t.set(r,6,n,!0),t.set(6,r,n,!0)}}function yf(t,e){let r=uf.getPositions(e);for(let n=0;n<r.length;n++){let s=r[n][0],i=r[n][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 Sf(t,e){let r=t.size,n=Rr.getEncodedBits(e),s,i,o;for(let a=0;a<18;a++)s=Math.floor(a/3),i=a%3+r-8-3,o=(n>>a&1)===1,t.set(s,i,o,!0),t.set(i,s,o,!0)}function Xn(t,e,r){let n=t.size,s=hf.getEncodedBits(e,r),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(n-15+i,8,o,!0),i<8?t.set(8,n-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(n-8,8,1,!0)}function _f(t,e){let r=t.size,n=-1,s=r-1,i=7,o=0;for(let a=r-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+=n,s<0||r<=s){s-=n,n=-n;break}}}function vf(t,e,r){let n=new lf;r.forEach(function(l){n.put(l.mode.bit,4),n.put(l.getLength(),pf.getCharCountIndicator(l.mode,t)),l.write(n)});let s=Lr.getSymbolTotalCodewords(t),i=Qn.getTotalCodewordsCount(t,e),o=(s-i)*8;for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let a=(o-n.getLengthInBits())/8;for(let l=0;l<a;l++)n.put(l%2?17:236,8);return wf(n,t,e)}function wf(t,e,r){let n=Lr.getSymbolTotalCodewords(e),s=Qn.getTotalCodewordsCount(e,r),i=n-s,o=Qn.getBlocksCount(e,r),a=n%o,l=o-a,c=Math.floor(n/o),u=Math.floor(i/o),d=u+1,f=c-u,h=new ff(f),p=0,g=new Array(o),y=new Array(o),S=0,U=new Uint8Array(t.buffer);for(let ie=0;ie<o;ie++){let $e=ie<l?u:d;g[ie]=U.slice(p,p+$e),y[ie]=h.encode(g[ie]),p+=$e,S=Math.max(S,$e)}let se=new Uint8Array(n),E=0,M,Y;for(M=0;M<S;M++)for(Y=0;Y<o;Y++)M<g[Y].length&&(se[E++]=g[Y][M]);for(M=0;M<f;M++)for(Y=0;Y<o;Y++)se[E++]=y[Y][M];return se}function bf(t,e,r,n){let s;if(Array.isArray(t))s=Kn.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=Kn.rawSplit(t);c=Rr.getBestVersionForData(u,r)}s=Kn.fromString(t,c||40)}else throw new Error("Invalid data");let i=Rr.getBestVersionForData(s,r);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 Be(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Be),t.emit("wsClientError",o,n,e)}else Mt(n,r,s,i)}});var Or=y((Em,po)=>{po.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var ve=y(De=>{var Br,Bd=[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];De.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};De.getSymbolTotalCodewords=function(e){return Bd[e]};De.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};De.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Br=e};De.isKanjiModeEnabled=function(){return typeof Br<"u"};De.toSJIS=function(e){return Br(e)}});var An=y(X=>{X.L={bit:1};X.M={bit:0};X.Q={bit:3};X.H={bit:2};function Dd(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return X.L;case"m":case"medium":return X.M;case"q":case"quartile":return X.Q;case"h":case"high":return X.H;default:throw new Error("Unknown EC Level: "+t)}}X.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};X.from=function(e,n){if(X.isValid(e))return e;try{return Dd(e)}catch{return n}}});var mo=y((Rm,go)=>{function ho(){this.buffer=[],this.length=0}ho.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++}};go.exports=ho});var So=y((Lm,yo)=>{function Nt(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)}Nt.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};Nt.prototype.get=function(t,e){return this.data[t*this.size+e]};Nt.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};Nt.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};yo.exports=Nt});var vo=y(kn=>{var Hd=ve().getSymbolSize;kn.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=Hd(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()};kn.getPositions=function(e){let n=[],r=kn.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 bo=y(wo=>{var Fd=ve().getSymbolSize,_o=7;wo.getPositions=function(e){let n=Fd(e);return[[0,0],[n-_o,0],[0,n-_o]]}});var Io=y(A=>{A.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var He={N1:3,N2:3,N3:40,N4:10};A.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};A.from=function(e){return A.isValid(e)?parseInt(e,10):void 0};A.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+=He.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(r+=He.N1+(i-5)),a=u,i=1)}s>=5&&(r+=He.N1+(s-5)),i>=5&&(r+=He.N1+(i-5))}return r};A.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*He.N2};A.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*He.N3};A.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)*He.N4};function Ud(t,e,n){switch(t){case A.Patterns.PATTERN000:return(e+n)%2===0;case A.Patterns.PATTERN001:return e%2===0;case A.Patterns.PATTERN010:return n%3===0;case A.Patterns.PATTERN011:return(e+n)%3===0;case A.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case A.Patterns.PATTERN101:return e*n%2+e*n%3===0;case A.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case A.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}A.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,Ud(e,i,s))};A.getBestMask=function(e,n){let r=Object.keys(A.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){n(o),A.applyMask(o,e);let a=A.getPenaltyN1(e)+A.getPenaltyN2(e)+A.getPenaltyN3(e)+A.getPenaltyN4(e);A.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var Hr=y(Dr=>{var _e=An(),xn=[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],Tn=[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];Dr.getBlocksCount=function(e,n){switch(n){case _e.L:return xn[(e-1)*4+0];case _e.M:return xn[(e-1)*4+1];case _e.Q:return xn[(e-1)*4+2];case _e.H:return xn[(e-1)*4+3];default:return}};Dr.getTotalCodewordsCount=function(e,n){switch(n){case _e.L:return Tn[(e-1)*4+0];case _e.M:return Tn[(e-1)*4+1];case _e.Q:return Tn[(e-1)*4+2];case _e.H:return Tn[(e-1)*4+3];default:return}}});var Ao=y(Cn=>{var Ot=new Uint8Array(512),En=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)Ot[n]=e,En[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)Ot[n]=Ot[n-255]})();Cn.log=function(e){if(e<1)throw new Error("log("+e+")");return En[e]};Cn.exp=function(e){return Ot[e]};Cn.mul=function(e,n){return e===0||n===0?0:Ot[En[e]+En[n]]}});var ko=y(Bt=>{var Fr=Ao();Bt.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]^=Fr.mul(e[s],n[i]);return r};Bt.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]^=Fr.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};Bt.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=Bt.mul(n,new Uint8Array([1,Fr.exp(r)]));return n}});var Eo=y((Fm,To)=>{var xo=ko();function Ur(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Ur.prototype.initialize=function(e){this.degree=e,this.genPoly=xo.generateECPolynomial(this.degree)};Ur.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=xo.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};To.exports=Ur});var qr=y(Co=>{Co.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Wr=y(ge=>{var Po="[0-9]+",qd="[A-Z $%*+\\-./:]+",Dt="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Dt=Dt.replace(/u/g,"\\u");var Wd="(?:(?![A-Z0-9 $%*+\\-./:]|"+Dt+`)(?:.|[\r
8
+ ]))+`;ge.KANJI=new RegExp(Dt,"g");ge.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");ge.BYTE=new RegExp(Wd,"g");ge.NUMERIC=new RegExp(Po,"g");ge.ALPHANUMERIC=new RegExp(qd,"g");var jd=new RegExp("^"+Dt+"$"),Gd=new RegExp("^"+Po+"$"),$d=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");ge.testKanji=function(e){return jd.test(e)};ge.testNumeric=function(e){return Gd.test(e)};ge.testAlphanumeric=function(e){return $d.test(e)}});var we=y(P=>{var zd=qr(),jr=Wr();P.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};P.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};P.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};P.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};P.MIXED={bit:-1};P.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!zd.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};P.getBestModeForData=function(e){return jr.testNumeric(e)?P.NUMERIC:jr.testAlphanumeric(e)?P.ALPHANUMERIC:jr.testKanji(e)?P.KANJI:P.BYTE};P.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};P.isValid=function(e){return e&&e.bit&&e.ccBits};function Vd(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return P.NUMERIC;case"alphanumeric":return P.ALPHANUMERIC;case"kanji":return P.KANJI;case"byte":return P.BYTE;default:throw new Error("Unknown mode: "+t)}}P.from=function(e,n){if(P.isValid(e))return e;try{return Vd(e)}catch{return n}}});var Oo=y(Fe=>{var Pn=ve(),Yd=Hr(),Ro=An(),be=we(),Gr=qr(),Mo=7973,Lo=Pn.getBCHDigit(Mo);function Jd(t,e,n){for(let r=1;r<=40;r++)if(e<=Fe.getCapacity(r,n,t))return r}function No(t,e){return be.getCharCountIndicator(t,e)+4}function Kd(t,e){let n=0;return t.forEach(function(r){let s=No(r.mode,e);n+=s+r.getBitsLength()}),n}function Xd(t,e){for(let n=1;n<=40;n++)if(Kd(t,n)<=Fe.getCapacity(n,e,be.MIXED))return n}Fe.from=function(e,n){return Gr.isValid(e)?parseInt(e,10):n};Fe.getCapacity=function(e,n,r){if(!Gr.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=be.BYTE);let s=Pn.getSymbolTotalCodewords(e),i=Yd.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===be.MIXED)return o;let a=o-No(r,e);switch(r){case be.NUMERIC:return Math.floor(a/10*3);case be.ALPHANUMERIC:return Math.floor(a/11*2);case be.KANJI:return Math.floor(a/13);case be.BYTE:default:return Math.floor(a/8)}};Fe.getBestVersionForData=function(e,n){let r,s=Ro.from(n,Ro.M);if(Array.isArray(e)){if(e.length>1)return Xd(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return Jd(r.mode,r.getLength(),s)};Fe.getEncodedBits=function(e){if(!Gr.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;Pn.getBCHDigit(n)-Lo>=0;)n^=Mo<<Pn.getBCHDigit(n)-Lo;return e<<12|n}});var Fo=y(Ho=>{var $r=ve(),Do=1335,Zd=21522,Bo=$r.getBCHDigit(Do);Ho.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;$r.getBCHDigit(s)-Bo>=0;)s^=Do<<$r.getBCHDigit(s)-Bo;return(r<<10|s)^Zd}});var qo=y(($m,Uo)=>{var Qd=we();function tt(t){this.mode=Qd.NUMERIC,this.data=t.toString()}tt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};tt.prototype.getLength=function(){return this.data.length};tt.prototype.getBitsLength=function(){return tt.getBitsLength(this.data.length)};tt.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))};Uo.exports=tt});var jo=y((zm,Wo)=>{var ef=we(),zr=["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 nt(t){this.mode=ef.ALPHANUMERIC,this.data=t}nt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};nt.prototype.getLength=function(){return this.data.length};nt.prototype.getBitsLength=function(){return nt.getBitsLength(this.data.length)};nt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=zr.indexOf(this.data[n])*45;r+=zr.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(zr.indexOf(this.data[n]),6)};Wo.exports=nt});var $o=y((Vm,Go)=>{var tf=we();function rt(t){this.mode=tf.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}rt.getBitsLength=function(e){return e*8};rt.prototype.getLength=function(){return this.data.length};rt.prototype.getBitsLength=function(){return rt.getBitsLength(this.data.length)};rt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Go.exports=rt});var Vo=y((Ym,zo)=>{var nf=we(),rf=ve();function st(t){this.mode=nf.KANJI,this.data=t}st.getBitsLength=function(e){return e*13};st.prototype.getLength=function(){return this.data.length};st.prototype.getBitsLength=function(){return st.getBitsLength(this.data.length)};st.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=rf.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)}};zo.exports=st});var Yo=y((Jm,Vr)=>{"use strict";var Ht={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=Ht.PriorityQueue.make();i.push(e,0);for(var o,a,l,c,u,d,f,p,h;!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],h=typeof s[l]>"u",(h||p>f)&&(s[l]=f,i.push(l,f),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var g=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(g)}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=Ht.single_source_shortest_paths(t,e,n);return Ht.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=Ht.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 Vr<"u"&&(Vr.exports=Ht)});var na=y(it=>{var I=we(),Xo=qo(),Zo=jo(),Qo=$o(),ea=Vo(),Ft=Wr(),Rn=ve(),sf=Yo();function Jo(t){return unescape(encodeURIComponent(t)).length}function Ut(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 ta(t){let e=Ut(Ft.NUMERIC,I.NUMERIC,t),n=Ut(Ft.ALPHANUMERIC,I.ALPHANUMERIC,t),r,s;return Rn.isKanjiModeEnabled()?(r=Ut(Ft.BYTE,I.BYTE,t),s=Ut(Ft.KANJI,I.KANJI,t)):(r=Ut(Ft.BYTE_KANJI,I.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 Yr(t,e){switch(e){case I.NUMERIC:return Xo.getBitsLength(t);case I.ALPHANUMERIC:return Zo.getBitsLength(t);case I.KANJI:return ea.getBitsLength(t);case I.BYTE:return Qo.getBitsLength(t)}}function of(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 af(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case I.NUMERIC:e.push([r,{data:r.data,mode:I.ALPHANUMERIC,length:r.length},{data:r.data,mode:I.BYTE,length:r.length}]);break;case I.ALPHANUMERIC:e.push([r,{data:r.data,mode:I.BYTE,length:r.length}]);break;case I.KANJI:e.push([r,{data:r.data,mode:I.BYTE,length:Jo(r.data)}]);break;case I.BYTE:e.push([{data:r.data,mode:I.BYTE,length:Jo(r.data)}])}}return e}function lf(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]=Yr(n[f].lastCount+c.length,c.mode)-Yr(n[f].lastCount,c.mode),n[f].lastCount+=c.length):(n[f]&&(n[f].lastCount=c.length),r[f][u]=Yr(c.length,c.mode)+4+I.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 Ko(t,e){let n,r=I.getBestModeForData(t);if(n=I.from(e,r),n!==I.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+I.toString(n)+`.
10
+ Suggested mode is: `+I.toString(r));switch(n===I.KANJI&&!Rn.isKanjiModeEnabled()&&(n=I.BYTE),n){case I.NUMERIC:return new Xo(t);case I.ALPHANUMERIC:return new Zo(t);case I.KANJI:return new ea(t);case I.BYTE:return new Qo(t)}}it.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(Ko(r,null)):r.data&&n.push(Ko(r.data,r.mode)),n},[])};it.fromString=function(e,n){let r=ta(e,Rn.isKanjiModeEnabled()),s=af(r),i=lf(s,n),o=sf.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return it.fromArray(of(a))};it.rawSplit=function(e){return it.fromArray(ta(e,Rn.isKanjiModeEnabled()))}});var es=y(ra=>{var Mn=ve(),Jr=An(),cf=mo(),uf=So(),df=vo(),ff=bo(),Zr=Io(),Qr=Hr(),pf=Eo(),Ln=Oo(),hf=Fo(),gf=we(),Kr=na();function mf(t,e){let n=t.size,r=ff.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 yf(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 Sf(t,e){let n=df.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 vf(t,e){let n=t.size,r=Ln.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 Xr(t,e,n){let r=t.size,s=hf.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 _f(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 wf(t,e,n){let r=new cf;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),gf.getCharCountIndicator(l.mode,t)),l.write(r)});let s=Mn.getSymbolTotalCodewords(t),i=Qr.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 bf(r,t,e)}function bf(t,e,n){let r=Mn.getSymbolTotalCodewords(e),s=Qr.getTotalCodewordsCount(e,n),i=r-s,o=Qr.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 pf(f),h=0,g=new Array(o),m=new Array(o),S=0,U=new Uint8Array(t.buffer);for(let ie=0;ie<o;ie++){let ze=ie<l?u:d;g[ie]=U.slice(h,h+ze),m[ie]=p.encode(g[ie]),h+=ze,S=Math.max(S,ze)}let se=new Uint8Array(r),T=0,M,Y;for(M=0;M<S;M++)for(Y=0;Y<o;Y++)M<g[Y].length&&(se[T++]=g[Y][M]);for(M=0;M<f;M++)for(Y=0;Y<o;Y++)se[T++]=m[Y][M];return se}function If(t,e,n,r){let s;if(Array.isArray(t))s=Kr.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=Kr.rawSplit(t);c=Ln.getBestVersionForData(u,n)}s=Kr.fromString(t,c||40)}else throw new Error("Invalid data");let i=Ln.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=vf(e,r,s),a=Lr.getSymbolSize(e),l=new cf(a);return gf(l,e),mf(l),yf(l,e),Xn(l,r,0),e>=7&&Sf(l,e),_f(l,o),isNaN(n)&&(n=Zn.getBestMask(l,Xn.bind(null,l,r))),Zn.applyMask(n,l),Xn(l,r,n),{modules:l,version:e,errorCorrectionLevel:r,maskPattern:n,segments:s}}na.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=Jn.M,s,i;return typeof r<"u"&&(n=Jn.from(r.errorCorrectionLevel,Jn.M),s=Rr.from(r.version),i=Zn.from(r.maskPattern),r.toSJISFunc&&Lr.setToSJISFunction(r.toSJISFunc)),bf(e,s,n,i)}});var ts=m((Vm,ia)=>{"use strict";var If=require("util"),sa=require("stream"),re=ia.exports=function(){sa.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};If.inherits(re,sa);re.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))};re.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let r;return Buffer.isBuffer(t)?r=t:r=Buffer.from(t,e||this._encoding),this._buffers.push(r),this._buffered+=r.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};re.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()))};re.prototype.destroySoon=re.prototype.end;re.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};re.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};re.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))};re.prototype._processRead=function(t){this._reads.shift();let e=0,r=0,n=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[r++],i=Math.min(s.length,t.length-e);s.copy(n,e,0,i),e+=i,i!==s.length&&(this._buffers[--r]=s.slice(i))}r>0&&this._buffers.splice(0,r),this._buffered-=t.length,t.func.call(this,n)};re.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 ns=m(rs=>{"use strict";var Ie=[{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]}];rs.getImagePasses=function(t,e){let r=[],n=t%8,s=e%8,i=(t-n)/8,o=(e-s)/8;for(let a=0;a<Ie.length;a++){let l=Ie[a],c=i*l.x.length,u=o*l.y.length;for(let d=0;d<l.x.length&&l.x[d]<n;d++)c++;for(let d=0;d<l.y.length&&l.y[d]<s;d++)u++;c>0&&u>0&&r.push({width:c,height:u,index:a})}return r};rs.getInterlaceIterator=function(t){return function(e,r,n){let s=e%Ie[n].x.length,i=(e-s)/Ie[n].x.length*8+Ie[n].x[s],o=r%Ie[n].y.length,a=(r-o)/Ie[n].y.length*8+Ie[n].y[o];return i*4+a*t*4}}});var ss=m((Jm,oa)=>{"use strict";oa.exports=function(e,r,n){let s=e+r-n,i=Math.abs(s-e),o=Math.abs(s-r),a=Math.abs(s-n);return i<=o&&i<=a?e:o<=a?r:n}});var is=m((Km,la)=>{"use strict";var xf=ns(),Tf=ss();function aa(t,e,r){let n=t*e;return r!==8&&(n=Math.ceil(n/(8/r))),n}var ot=la.exports=function(t,e){let r=t.width,n=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=xf.getImagePasses(r,n);for(let l=0;l<a.length;l++)this._images.push({byteWidth:aa(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:aa(r,i,o),height:n,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};ot.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ot.prototype._unFilterType1=function(t,e,r){let n=this._xComparison,s=n-1;for(let i=0;i<r;i++){let o=t[1+i],a=i>s?e[i-n]:0;e[i]=o+a}};ot.prototype._unFilterType2=function(t,e,r){let n=this._lastLine;for(let s=0;s<r;s++){let i=t[1+s],o=n?n[s]:0;e[s]=i+o}};ot.prototype._unFilterType3=function(t,e,r){let n=this._xComparison,s=n-1,i=this._lastLine;for(let o=0;o<r;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-n]:0,u=Math.floor((c+l)/2);e[o]=a+u}};ot.prototype._unFilterType4=function(t,e,r){let n=this._xComparison,s=n-1,i=this._lastLine;for(let o=0;o<r;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-n]:0,u=o>s&&i?i[o-n]:0,d=Tf(c,l,u);e[o]=a+d}};ot.prototype._reverseFilterLine=function(t){let e=t[0],r,n=this._images[this._imageIndex],s=n.byteWidth;if(e===0)r=t.slice(1,s+1);else switch(r=Buffer.alloc(s),e){case 1:this._unFilterType1(t,r,s);break;case 2:this._unFilterType2(t,r,s);break;case 3:this._unFilterType3(t,r,s);break;case 4:this._unFilterType4(t,r,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(r),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=r,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var da=m((Xm,ua)=>{"use strict";var kf=require("util"),ca=ts(),Ef=is(),Af=ua.exports=function(t){ca.call(this);let e=[],r=this;this._filter=new Ef(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){r.emit("complete",Buffer.concat(e))}}),this._filter.start()};kf.inherits(Af,ca)});var at=m((Zm,fa)=>{"use strict";fa.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 ls=m((Qm,ha)=>{"use strict";var os=[];(function(){for(let t=0;t<256;t++){let e=t;for(let r=0;r<8;r++)e&1?e=3988292384^e>>>1:e=e>>>1;os[t]=e}})();var as=ha.exports=function(){this._crc=-1};as.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=os[(this._crc^t[e])&255]^this._crc>>>8;return!0};as.prototype.crc32=function(){return this._crc^-1};as.crc32=function(t){let e=-1;for(let r=0;r<t.length;r++)e=os[(e^t[r])&255]^e>>>8;return e^-1}});var cs=m((ey,pa)=>{"use strict";var R=at(),Cf=ls(),O=pa.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[R.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[R.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[R.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[R.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[R.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[R.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(){}};O.prototype.start=function(){this.read(R.PNG_SIGNATURE.length,this._parseSignature.bind(this))};O.prototype._parseSignature=function(t){let e=R.PNG_SIGNATURE;for(let r=0;r<e.length;r++)if(t[r]!==e[r]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};O.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n="";for(let i=4;i<8;i++)n+=String.fromCharCode(t[i]);let s=!!(t[4]&32);if(!this._hasIHDR&&r!==R.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Cf,this._crc.write(Buffer.from(n)),this._chunks[r])return this._chunks[r](e);if(!s){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};O.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};O.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};O.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),r=this._crc.crc32();if(this._options.checkCRC&&r!==e){this.error(new Error("Crc error - "+e+" - "+r));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};O.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};O.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n=t[8],s=t[9],i=t[10],o=t[11],a=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(s in R.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=R.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:n,interlace:!!a,palette:!!(s&R.COLORTYPE_PALETTE),color:!!(s&R.COLORTYPE_COLOR),alpha:!!(s&R.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};O.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};O.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let r=0;r<e;r++)this._palette.push([t[r*3],t[r*3+1],t[r*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};O.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};O.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===R.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===R.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===R.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};O.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};O.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/R.GAMMA_DIVISION),this._handleChunkEnd()};O.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};O.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===R.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let r=t-e.length;r>0?this._handleIDAT(r):this._handleChunkEnd()};O.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};O.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var us=m(ma=>{"use strict";var ga=ns(),Pf=[function(){},function(t,e,r,n){if(n===e.length)throw new Error("Ran out of data");let s=e[n];t[r]=s,t[r+1]=s,t[r+2]=s,t[r+3]=255},function(t,e,r,n){if(n+1>=e.length)throw new Error("Ran out of data");let s=e[n];t[r]=s,t[r+1]=s,t[r+2]=s,t[r+3]=e[n+1]},function(t,e,r,n){if(n+2>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=255},function(t,e,r,n){if(n+3>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=e[n+3]}],Rf=[function(){},function(t,e,r,n){let s=e[0];t[r]=s,t[r+1]=s,t[r+2]=s,t[r+3]=n},function(t,e,r){let n=e[0];t[r]=n,t[r+1]=n,t[r+2]=n,t[r+3]=e[1]},function(t,e,r,n){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=n},function(t,e,r){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=e[3]}];function Lf(t,e){let r=[],n=0;function s(){if(n===t.length)throw new Error("Ran out of data");let i=t[n];n++;let o,a,l,c,u,d,f,h;switch(e){default:throw new Error("unrecognised depth");case 16:f=t[n],n++,r.push((i<<8)+f);break;case 4:f=i&15,h=i>>4,r.push(h,f);break;case 2:u=i&3,d=i>>2&3,f=i>>4&3,h=i>>6&3,r.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,r.push(h,f,d,u,c,l,a,o);break}}return{get:function(i){for(;r.length<i;)s();let o=r.slice(0,i);return r=r.slice(i),o},resetAfterLine:function(){r.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function Mf(t,e,r,n,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=r(u,c,l);Pf[n](e,s,d,i),i+=n}return i}function Nf(t,e,r,n,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(n),f=r(u,c,l);Rf[n](e,d,f,i)}s.resetAfterLine()}}ma.dataToBitMap=function(t,e){let r=e.width,n=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=Lf(t,s));let l;s<=8?l=Buffer.alloc(r*n*4):l=new Uint16Array(r*n*4);let c=Math.pow(2,s)-1,u=0,d,f;if(o)d=ga.getImagePasses(r,n),f=ga.getInterlaceIterator(r,n);else{let h=0;f=function(){let p=h;return h+=4,p},d=[{width:r,height:n}]}for(let h=0;h<d.length;h++)s===8?u=Mf(d[h],l,f,i,t,u):Nf(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 ds=m((ry,ya)=>{"use strict";function Of(t,e,r,n,s){let i=0;for(let o=0;o<n;o++)for(let a=0;a<r;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 Bf(t,e,r,n,s){let i=0;for(let o=0;o<n;o++)for(let a=0;a<r;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 Df(t,e,r,n,s){let i=255,o=Math.pow(2,s)-1,a=0;for(let l=0;l<n;l++)for(let c=0;c<r;c++){for(let u=0;u<4;u++)e[a+u]=Math.floor(t[a+u]*i/o+.5);a+=4}}ya.exports=function(t,e){let r=e.depth,n=e.width,s=e.height,i=e.colorType,o=e.transColor,a=e.palette,l=t;return i===3?Of(t,l,n,s,a):(o&&Bf(t,l,n,s,o),r!==8&&(r===16&&(l=Buffer.alloc(n*s*4)),Df(t,l,n,s,r))),l}});var va=m((ny,_a)=>{"use strict";var Hf=require("util"),fs=require("zlib"),Sa=ts(),Ff=da(),Uf=cs(),qf=us(),Wf=ds(),ae=_a.exports=function(t){Sa.call(this),this._parser=new Uf(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()};Hf.inherits(ae,Sa);ae.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};ae.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=fs.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let r=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(r,fs.Z_MIN_CHUNK);this._inflate=fs.createInflate({chunkSize:n});let s=r,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)};ae.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Ff(this._bitmapInfo)};ae.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ae.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ae.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ae.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ae.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ae.prototype._complete=function(t){if(this.errord)return;let e;try{let r=qf.dataToBitMap(t,this._bitmapInfo);e=Wf(r,this._bitmapInfo),r=null}catch(r){this._handleError(r);return}this.emit("parsed",e)}});var ba=m((sy,wa)=>{"use strict";var Z=at();wa.exports=function(t,e,r,n){let s=[Z.COLORTYPE_COLOR_ALPHA,Z.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let p=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&p)return t}let i=n.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=Z.COLORTYPE_TO_BPP_MAP[n.inputColorType];a===4&&!n.inputHasAlpha&&(a=3);let l=Z.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*r*l),u=0,d=0,f=n.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 p,g,y,S=o;switch(n.inputColorType){case Z.COLORTYPE_COLOR_ALPHA:S=i[u+3],p=i[u],g=i[u+1],y=i[u+2];break;case Z.COLORTYPE_COLOR:p=i[u],g=i[u+1],y=i[u+2];break;case Z.COLORTYPE_ALPHA:S=i[u+1],p=i[u],g=p,y=p;break;case Z.COLORTYPE_GRAYSCALE:p=i[u],g=p,y=p;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(s||(S/=o,p=Math.min(Math.max(Math.round((1-S)*f.red+S*p),0),o),g=Math.min(Math.max(Math.round((1-S)*f.green+S*g),0),o),y=Math.min(Math.max(Math.round((1-S)*f.blue+S*y),0),o))),{red:p,green:g,blue:y,alpha:S}}for(let p=0;p<r;p++)for(let g=0;g<e;g++){let y=h(i,u);switch(n.colorType){case Z.COLORTYPE_COLOR_ALPHA:case Z.COLORTYPE_COLOR:n.bitDepth===8?(c[d]=y.red,c[d+1]=y.green,c[d+2]=y.blue,s&&(c[d+3]=y.alpha)):(c.writeUInt16BE(y.red,d),c.writeUInt16BE(y.green,d+2),c.writeUInt16BE(y.blue,d+4),s&&c.writeUInt16BE(y.alpha,d+6));break;case Z.COLORTYPE_ALPHA:case Z.COLORTYPE_GRAYSCALE:{let S=(y.red+y.green+y.blue)/3;n.bitDepth===8?(c[d]=S,s&&(c[d+1]=y.alpha)):(c.writeUInt16BE(S,d),s&&c.writeUInt16BE(y.alpha,d+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}u+=a,d+=l}return c}});var Ta=m((iy,xa)=>{"use strict";var Ia=ss();function jf(t,e,r,n,s){for(let i=0;i<r;i++)n[s+i]=t[e+i]}function Gf(t,e,r){let n=0,s=e+r;for(let i=e;i<s;i++)n+=Math.abs(t[i]);return n}function zf(t,e,r,n,s,i){for(let o=0;o<r;o++){let a=o>=i?t[e+o-i]:0,l=t[e+o]-a;n[s+o]=l}}function $f(t,e,r,n){let s=0;for(let i=0;i<r;i++){let o=i>=n?t[e+i-n]:0,a=t[e+i]-o;s+=Math.abs(a)}return s}function Vf(t,e,r,n,s){for(let i=0;i<r;i++){let o=e>0?t[e+i-r]:0,a=t[e+i]-o;n[s+i]=a}}function Yf(t,e,r){let n=0,s=e+r;for(let i=e;i<s;i++){let o=e>0?t[i-r]:0,a=t[i]-o;n+=Math.abs(a)}return n}function Jf(t,e,r,n,s,i){for(let o=0;o<r;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-r]:0,c=t[e+o]-(a+l>>1);n[s+o]=c}}function Kf(t,e,r,n){let s=0;for(let i=0;i<r;i++){let o=i>=n?t[e+i-n]:0,a=e>0?t[e+i-r]:0,l=t[e+i]-(o+a>>1);s+=Math.abs(l)}return s}function Xf(t,e,r,n,s,i){for(let o=0;o<r;o++){let a=o>=i?t[e+o-i]:0,l=e>0?t[e+o-r]:0,c=e>0&&o>=i?t[e+o-(r+i)]:0,u=t[e+o]-Ia(a,l,c);n[s+o]=u}}function Zf(t,e,r,n){let s=0;for(let i=0;i<r;i++){let o=i>=n?t[e+i-n]:0,a=e>0?t[e+i-r]:0,l=e>0&&i>=n?t[e+i-(r+n)]:0,c=t[e+i]-Ia(o,a,l);s+=Math.abs(c)}return s}var Qf={0:jf,1:zf,2:Vf,3:Jf,4:Xf},eh={0:Gf,1:$f,2:Yf,3:Kf,4:Zf};xa.exports=function(t,e,r,n,s){let i;if(!("filterType"in n)||n.filterType===-1)i=[0,1,2,3,4];else if(typeof n.filterType=="number")i=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(s*=2);let o=e*s,a=0,l=0,c=Buffer.alloc((o+1)*r),u=i[0];for(let d=0;d<r;d++){if(i.length>1){let f=1/0;for(let h=0;h<i.length;h++){let p=eh[i[h]](t,l,o,s);p<f&&(u=i[h],f=p)}}c[a]=u,a++,Qf[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var hs=m((oy,ka)=>{"use strict";var H=at(),th=ls(),rh=ba(),nh=Ta(),sh=require("zlib"),xe=ka.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||sh.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:H.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:H.COLORTYPE_COLOR_ALPHA,[H.COLORTYPE_GRAYSCALE,H.COLORTYPE_COLOR,H.COLORTYPE_COLOR_ALPHA,H.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([H.COLORTYPE_GRAYSCALE,H.COLORTYPE_COLOR,H.COLORTYPE_COLOR_ALPHA,H.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")};xe.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};xe.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};xe.prototype.filterData=function(t,e,r){let n=rh(t,e,r,this._options),s=H.COLORTYPE_TO_BPP_MAP[this._options.colorType];return nh(n,e,r,this._options,s)};xe.prototype._packChunk=function(t,e){let r=e?e.length:0,n=Buffer.alloc(r+12);return n.writeUInt32BE(r,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE(th.crc32(n.slice(4,n.length-4)),n.length-4),n};xe.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*H.GAMMA_DIVISION),0),this._packChunk(H.TYPE_gAMA,e)};xe.prototype.packIHDR=function(t,e){let r=Buffer.alloc(13);return r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),r[8]=this._options.bitDepth,r[9]=this._options.colorType,r[10]=0,r[11]=0,r[12]=0,this._packChunk(H.TYPE_IHDR,r)};xe.prototype.packIDAT=function(t){return this._packChunk(H.TYPE_IDAT,t)};xe.prototype.packIEND=function(){return this._packChunk(H.TYPE_IEND,null)}});var Pa=m((ay,Ca)=>{"use strict";var ih=require("util"),Ea=require("stream"),oh=at(),ah=hs(),Aa=Ca.exports=function(t){Ea.call(this);let e=t||{};this._packer=new ah(e),this._deflate=this._packer.createDeflate(),this.readable=!0};ih.inherits(Aa,Ea);Aa.prototype.pack=function(t,e,r,n){this.emit("data",Buffer.from(oh.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,r)),n&&this.emit("data",this._packer.packGAMA(n));let s=this._packer.filterData(t,e,r);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 Ba=m((qt,Oa)=>{"use strict";var Ra=require("assert").ok,lt=require("zlib"),lh=require("util"),La=require("buffer").kMaxLength;function Ue(t){if(!(this instanceof Ue))return new Ue(t);t&&t.chunkSize<lt.Z_MIN_CHUNK&&(t.chunkSize=lt.Z_MIN_CHUNK),lt.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 ch(t){return new Ue(t)}function Ma(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ue.prototype._processChunk=function(t,e,r){if(typeof r=="function")return lt.Inflate._processChunk.call(this,t,e,r);let n=this,s=t&&t.length,i=this._chunkSize-this._offset,o=this._maxLength,a=0,l=[],c=0,u;this.on("error",function(p){u=p});function d(p,g){if(n._hadError)return;let y=i-g;if(Ra(y>=0,"have should not go down"),y>0){let S=n._buffer.slice(n._offset,n._offset+y);if(n._offset+=y,S.length>o&&(S=S.slice(0,o)),l.push(S),c+=S.length,o-=S.length,o===0)return!1}return(g===0||n._offset>=n._chunkSize)&&(i=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),g===0?(a+=s-p,s=p,!0):!1}Ra(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>=La)throw Ma(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+La.toString(16)+" bytes");let h=Buffer.concat(l,c);return Ma(this),h};lh.inherits(Ue,lt.Inflate);function uh(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let r=t._finishFlushFlag;return r==null&&(r=lt.Z_FINISH),t._processChunk(e,r)}function Na(t,e){return uh(new Ue(e),t)}Oa.exports=qt=Na;qt.Inflate=Ue;qt.createInflate=ch;qt.inflateSync=Na});var ps=m((ly,Ha)=>{"use strict";var Da=Ha.exports=function(t){this._buffer=t,this._reads=[]};Da.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Da.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 Ua=m(Fa=>{"use strict";var dh=ps(),fh=is();Fa.process=function(t,e){let r=[],n=new dh(t);return new fh(e,{read:n.read.bind(n),write:function(i){r.push(i)},complete:function(){}}).start(),n.process(),Buffer.concat(r)}});var Ga=m((uy,ja)=>{"use strict";var qa=!0,Wa=require("zlib"),hh=Ba();Wa.deflateSync||(qa=!1);var ph=ps(),gh=Ua(),mh=cs(),yh=us(),Sh=ds();ja.exports=function(t,e){if(!qa)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r;function n(E){r=E}let s;function i(E){s=E}function o(E){s.transColor=E}function a(E){s.palette=E}function l(){s.alpha=!0}let c;function u(E){c=E}let d=[];function f(E){d.push(E)}let h=new ph(t);if(new mh(e,{read:h.read.bind(h),error:n,metadata:i,gamma:u,palette:a,transColor:o,inflateData:f,simpleTransparency:l}).start(),h.process(),r)throw r;let g=Buffer.concat(d);d.length=0;let y;if(s.interlace)y=Wa.inflateSync(g);else{let M=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;y=hh(g,{chunkSize:M,maxLength:M})}if(g=null,!y||!y.length)throw new Error("bad png - invalid inflate data response");let S=gh.process(y,s);g=null;let U=yh.dataToBitMap(S,s);S=null;let se=Sh(U,s);return s.data=se,s.gamma=c||0,s}});var Ya=m((dy,Va)=>{"use strict";var za=!0,$a=require("zlib");$a.deflateSync||(za=!1);var _h=at(),vh=hs();Va.exports=function(t,e){if(!za)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=e||{},n=new vh(r),s=[];s.push(Buffer.from(_h.PNG_SIGNATURE)),s.push(n.packIHDR(t.width,t.height)),t.gamma&&s.push(n.packGAMA(t.gamma));let i=n.filterData(t.data,t.width,t.height),o=$a.deflateSync(i,n.getDeflateOptions());if(i=null,!o||!o.length)throw new Error("bad png - invalid compressed data response");return s.push(n.packIDAT(o)),s.push(n.packIEND()),Buffer.concat(s)}});var Ja=m(gs=>{"use strict";var wh=Ga(),bh=Ya();gs.read=function(t,e){return wh(t,e||{})};gs.write=function(t,e){return bh(t,e)}});var Za=m(Xa=>{"use strict";var Ih=require("util"),Ka=require("stream"),xh=va(),Th=Pa(),kh=Ja(),q=Xa.PNG=function(t){Ka.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 xh(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 Th(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"))};Ih.inherits(q,Ka);q.sync=kh;q.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)};q.prototype.parse=function(t,e){if(e){let r,n;r=function(s){this.removeListener("error",n),this.data=s,e(null,this)}.bind(this),n=function(s){this.removeListener("parsed",r),e(s,null)}.bind(this),this.once("parsed",r),this.once("error",n)}return this.end(t),this};q.prototype.write=function(t){return this._parser.write(t),!0};q.prototype.end=function(t){this._parser.end(t)};q.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};q.prototype._gamma=function(t){this.gamma=t};q.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};q.bitblt=function(t,e,r,n,s,i,o,a){if(r|=0,n|=0,s|=0,i|=0,o|=0,a|=0,r>t.width||n>t.height||r+s>t.width||n+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,(n+l)*t.width+r<<2,(n+l)*t.width+r+s<<2)};q.prototype.bitblt=function(t,e,r,n,s,i,o){return q.bitblt(this,t,e,r,n,s,i,o),this};q.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let r=0;r<t.width;r++){let n=t.width*e+r<<2;for(let s=0;s<3;s++){let i=t.data[n+s]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[n+s]=Math.round(i*255)}}t.gamma=0}};q.prototype.adjustGamma=function(){q.adjustGamma(this)}});var Wt=m(qe=>{function Qa(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(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}qe.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:n,scale:n?4:s,margin:r,color:{dark:Qa(e.color.dark||"#000000ff"),light:Qa(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};qe.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};qe.getImageWidth=function(e,r){let n=qe.getScale(e,r);return Math.floor((e+r.margin*2)*n)};qe.qrToImageData=function(e,r,n){let s=r.modules.size,i=r.modules.data,o=qe.getScale(s,n),a=Math.floor((s+n.margin*2)*o),l=n.margin*o,c=[n.color.light,n.color.dark];for(let u=0;u<a;u++)for(let d=0;d<a;d++){let f=(u*a+d)*4,h=n.color.light;if(u>=l&&d>=l&&u<a-l&&d<a-l){let p=Math.floor((u-l)/o),g=Math.floor((d-l)/o);h=c[i[p*s+g]?1:0]}e[f++]=h.r,e[f++]=h.g,e[f++]=h.b,e[f]=h.a}}});var el=m(le=>{var Eh=require("fs"),Ah=Za().PNG,ms=Wt();le.render=function(e,r){let n=ms.getOptions(r),s=n.rendererOpts,i=ms.getImageWidth(e.modules.size,n);s.width=i,s.height=i;let o=new Ah(s);return ms.qrToImageData(o.data,e,n),o};le.renderToDataURL=function(e,r,n){typeof n>"u"&&(n=r,r=void 0),le.renderToBuffer(e,r,function(s,i){s&&n(s);let o="data:image/png;base64,";o+=i.toString("base64"),n(null,o)})};le.renderToBuffer=function(e,r,n){typeof n>"u"&&(n=r,r=void 0);let s=le.render(e,r),i=[];s.on("error",n),s.on("data",function(o){i.push(o)}),s.on("end",function(){n(null,Buffer.concat(i))}),s.pack()};le.renderToFile=function(e,r,n,s){typeof s>"u"&&(s=n,n=void 0);let i=!1,o=(...l)=>{i||(i=!0,s.apply(null,l))},a=Eh.createWriteStream(e);a.on("error",o),a.on("close",o),le.renderToFileStream(a,r,n)};le.renderToFileStream=function(e,r,n){le.render(r,n).pack().pipe(e)}});var tl=m(Mr=>{var Ch=Wt(),Ph={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Rh={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Lh(t,e,r){return t&&e?r.BB:t&&!e?r.BW:!t&&e?r.WB:r.WW}Mr.render=function(t,e,r){let n=Ch.getOptions(e),s=Ph;(n.color.dark.hex==="#ffffff"||n.color.light.hex==="#000000")&&(s=Rh);let i=t.modules.size,o=t.modules.data,a="",l=Array(i+n.margin*2+1).join(s.WW);l=Array(n.margin/2+1).join(l+`
14
- `);let c=Array(n.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+=Lh(f,h,s)}a+=c+`
15
- `}return a+=l.slice(0,-1),typeof r=="function"&&r(null,a),a};Mr.renderToFile=function(e,r,n,s){typeof s>"u"&&(s=n,n=void 0);let i=require("fs"),o=Mr.render(r,n);i.writeFile(e,o,s)}});var nl=m(rl=>{rl.render=function(t,e,r){let n=t.modules.size,s=t.modules.data,i="\x1B[40m \x1B[0m",o="\x1B[47m \x1B[0m",a="",l=Array(n+3).join(o),c=Array(2).join(o);a+=l+`
16
- `;for(let u=0;u<n;++u){a+=o;for(let d=0;d<n;d++)a+=s[u*n+d]?i:o;a+=c+`
13
+ `);let o=wf(e,n,s),a=Mn.getSymbolSize(e),l=new uf(a);return mf(l,e),yf(l),Sf(l,e),Xr(l,n,0),e>=7&&vf(l,e),_f(l,o),isNaN(r)&&(r=Zr.getBestMask(l,Xr.bind(null,l,n))),Zr.applyMask(r,l),Xr(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}ra.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=Jr.M,s,i;return typeof n<"u"&&(r=Jr.from(n.errorCorrectionLevel,Jr.M),s=Ln.from(n.version),i=Zr.from(n.maskPattern),n.toSJISFunc&&Mn.setToSJISFunction(n.toSJISFunc)),If(e,s,r,i)}});var ts=y((Zm,ia)=>{"use strict";var Af=require("util"),sa=require("stream"),ne=ia.exports=function(){sa.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Af.inherits(ne,sa);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 rs=y(ns=>{"use strict";var Ie=[{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]}];ns.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<Ie.length;a++){let l=Ie[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};ns.getInterlaceIterator=function(t){return function(e,n,r){let s=e%Ie[r].x.length,i=(e-s)/Ie[r].x.length*8+Ie[r].x[s],o=n%Ie[r].y.length,a=(n-o)/Ie[r].y.length*8+Ie[r].y[o];return i*4+a*t*4}}});var ss=y((ey,oa)=>{"use strict";oa.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 is=y((ty,la)=>{"use strict";var kf=rs(),xf=ss();function aa(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var ot=la.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=kf.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:aa(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:aa(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};ot.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};ot.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}};ot.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}};ot.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}};ot.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=xf(c,l,u);e[o]=a+d}};ot.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 da=y((ny,ua)=>{"use strict";var Tf=require("util"),ca=ts(),Ef=is(),Cf=ua.exports=function(t){ca.call(this);let e=[],n=this;this._filter=new Ef(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};Tf.inherits(Cf,ca)});var at=y((ry,fa)=>{"use strict";fa.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 ls=y((sy,pa)=>{"use strict";var os=[];(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;os[t]=e}})();var as=pa.exports=function(){this._crc=-1};as.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=os[(this._crc^t[e])&255]^this._crc>>>8;return!0};as.prototype.crc32=function(){return this._crc^-1};as.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=os[(e^t[n])&255]^e>>>8;return e^-1}});var cs=y((iy,ha)=>{"use strict";var R=at(),Pf=ls(),O=ha.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[R.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[R.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[R.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[R.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[R.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[R.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(){}};O.prototype.start=function(){this.read(R.PNG_SIGNATURE.length,this._parseSignature.bind(this))};O.prototype._parseSignature=function(t){let e=R.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))};O.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!==R.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new Pf,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))};O.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};O.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};O.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))};O.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};O.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 R.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=R.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&R.COLORTYPE_PALETTE),color:!!(s&R.COLORTYPE_COLOR),alpha:!!(s&R.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};O.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};O.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()};O.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};O.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===R.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===R.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===R.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};O.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};O.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/R.GAMMA_DIVISION),this._handleChunkEnd()};O.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};O.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===R.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()};O.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};O.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var us=y(ma=>{"use strict";var ga=rs(),Rf=[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]}],Lf=[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 Mf(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 Nf(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);Rf[r](e,s,d,i),i+=r}return i}function Of(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);Lf[r](e,d,f,i)}s.resetAfterLine()}}ma.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=Mf(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=ga.getImagePasses(n,r),f=ga.getInterlaceIterator(n,r);else{let p=0;f=function(){let h=p;return p+=4,h},d=[{width:n,height:r}]}for(let p=0;p<d.length;p++)s===8?u=Nf(d[p],l,f,i,t,u):Of(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 ds=y((ay,ya)=>{"use strict";function Bf(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 Df(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 Hf(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}}ya.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?Bf(t,l,r,s,a):(o&&Df(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),Hf(t,l,r,s,n))),l}});var _a=y((ly,va)=>{"use strict";var Ff=require("util"),fs=require("zlib"),Sa=ts(),Uf=da(),qf=cs(),Wf=us(),jf=ds(),ae=va.exports=function(t){Sa.call(this),this._parser=new qf(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()};Ff.inherits(ae,Sa);ae.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};ae.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=fs.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,fs.Z_MIN_CHUNK);this._inflate=fs.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)};ae.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Uf(this._bitmapInfo)};ae.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ae.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ae.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ae.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ae.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ae.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Wf.dataToBitMap(t,this._bitmapInfo);e=jf(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var ba=y((cy,wa)=>{"use strict";var Z=at();wa.exports=function(t,e,n,r){let s=[Z.COLORTYPE_COLOR_ALPHA,Z.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let h=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(r.bitDepth===8||r.bitDepth===16&&h)return t}let i=r.bitDepth!==16?t:new Uint16Array(t.buffer),o=255,a=Z.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=Z.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 h,g,m,S=o;switch(r.inputColorType){case Z.COLORTYPE_COLOR_ALPHA:S=i[u+3],h=i[u],g=i[u+1],m=i[u+2];break;case Z.COLORTYPE_COLOR:h=i[u],g=i[u+1],m=i[u+2];break;case Z.COLORTYPE_ALPHA:S=i[u+1],h=i[u],g=h,m=h;break;case Z.COLORTYPE_GRAYSCALE:h=i[u],g=h,m=h;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(S/=o,h=Math.min(Math.max(Math.round((1-S)*f.red+S*h),0),o),g=Math.min(Math.max(Math.round((1-S)*f.green+S*g),0),o),m=Math.min(Math.max(Math.round((1-S)*f.blue+S*m),0),o))),{red:h,green:g,blue:m,alpha:S}}for(let h=0;h<n;h++)for(let g=0;g<e;g++){let m=p(i,u);switch(r.colorType){case Z.COLORTYPE_COLOR_ALPHA:case Z.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 Z.COLORTYPE_ALPHA:case Z.COLORTYPE_GRAYSCALE:{let S=(m.red+m.green+m.blue)/3;r.bitDepth===8?(c[d]=S,s&&(c[d+1]=m.alpha)):(c.writeUInt16BE(S,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 ka=y((uy,Aa)=>{"use strict";var Ia=ss();function Gf(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function $f(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function zf(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 Vf(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 Yf(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 Jf(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 Kf(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 Xf(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 Zf(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]-Ia(a,l,c);r[s+o]=u}}function Qf(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]-Ia(o,a,l);s+=Math.abs(c)}return s}var ep={0:Gf,1:zf,2:Yf,3:Kf,4:Zf},tp={0:$f,1:Vf,2:Jf,3:Xf,4:Qf};Aa.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 h=tp[i[p]](t,l,o,s);h<f&&(u=i[p],f=h)}}c[a]=u,a++,ep[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var ps=y((dy,xa)=>{"use strict";var H=at(),np=ls(),rp=ba(),sp=ka(),ip=require("zlib"),Ae=xa.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||ip.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:H.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:H.COLORTYPE_COLOR_ALPHA,[H.COLORTYPE_GRAYSCALE,H.COLORTYPE_COLOR,H.COLORTYPE_COLOR_ALPHA,H.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([H.COLORTYPE_GRAYSCALE,H.COLORTYPE_COLOR,H.COLORTYPE_COLOR_ALPHA,H.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")};Ae.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Ae.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Ae.prototype.filterData=function(t,e,n){let r=rp(t,e,n,this._options),s=H.COLORTYPE_TO_BPP_MAP[this._options.colorType];return sp(r,e,n,this._options,s)};Ae.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(np.crc32(r.slice(4,r.length-4)),r.length-4),r};Ae.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*H.GAMMA_DIVISION),0),this._packChunk(H.TYPE_gAMA,e)};Ae.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(H.TYPE_IHDR,n)};Ae.prototype.packIDAT=function(t){return this._packChunk(H.TYPE_IDAT,t)};Ae.prototype.packIEND=function(){return this._packChunk(H.TYPE_IEND,null)}});var Pa=y((fy,Ca)=>{"use strict";var op=require("util"),Ta=require("stream"),ap=at(),lp=ps(),Ea=Ca.exports=function(t){Ta.call(this);let e=t||{};this._packer=new lp(e),this._deflate=this._packer.createDeflate(),this.readable=!0};op.inherits(Ea,Ta);Ea.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(ap.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 Ba=y((qt,Oa)=>{"use strict";var Ra=require("assert").ok,lt=require("zlib"),cp=require("util"),La=require("buffer").kMaxLength;function Ue(t){if(!(this instanceof Ue))return new Ue(t);t&&t.chunkSize<lt.Z_MIN_CHUNK&&(t.chunkSize=lt.Z_MIN_CHUNK),lt.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 up(t){return new Ue(t)}function Ma(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ue.prototype._processChunk=function(t,e,n){if(typeof n=="function")return lt.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(h){u=h});function d(h,g){if(r._hadError)return;let m=i-g;if(Ra(m>=0,"have should not go down"),m>0){let S=r._buffer.slice(r._offset,r._offset+m);if(r._offset+=m,S.length>o&&(S=S.slice(0,o)),l.push(S),c+=S.length,o-=S.length,o===0)return!1}return(g===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),g===0?(a+=s-h,s=h,!0):!1}Ra(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>=La)throw Ma(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+La.toString(16)+" bytes");let p=Buffer.concat(l,c);return Ma(this),p};cp.inherits(Ue,lt.Inflate);function dp(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=lt.Z_FINISH),t._processChunk(e,n)}function Na(t,e){return dp(new Ue(e),t)}Oa.exports=qt=Na;qt.Inflate=Ue;qt.createInflate=up;qt.inflateSync=Na});var hs=y((py,Ha)=>{"use strict";var Da=Ha.exports=function(t){this._buffer=t,this._reads=[]};Da.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Da.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 Ua=y(Fa=>{"use strict";var fp=hs(),pp=is();Fa.process=function(t,e){let n=[],r=new fp(t);return new pp(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Ga=y((gy,ja)=>{"use strict";var qa=!0,Wa=require("zlib"),hp=Ba();Wa.deflateSync||(qa=!1);var gp=hs(),mp=Ua(),yp=cs(),Sp=us(),vp=ds();ja.exports=function(t,e){if(!qa)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(T){n=T}let s;function i(T){s=T}function o(T){s.transColor=T}function a(T){s.palette=T}function l(){s.alpha=!0}let c;function u(T){c=T}let d=[];function f(T){d.push(T)}let p=new gp(t);if(new yp(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 g=Buffer.concat(d);d.length=0;let m;if(s.interlace)m=Wa.inflateSync(g);else{let M=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;m=hp(g,{chunkSize:M,maxLength:M})}if(g=null,!m||!m.length)throw new Error("bad png - invalid inflate data response");let S=mp.process(m,s);g=null;let U=Sp.dataToBitMap(S,s);S=null;let se=vp(U,s);return s.data=se,s.gamma=c||0,s}});var Ya=y((my,Va)=>{"use strict";var $a=!0,za=require("zlib");za.deflateSync||($a=!1);var _p=at(),wp=ps();Va.exports=function(t,e){if(!$a)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 wp(n),s=[];s.push(Buffer.from(_p.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=za.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 Ja=y(gs=>{"use strict";var bp=Ga(),Ip=Ya();gs.read=function(t,e){return bp(t,e||{})};gs.write=function(t,e){return Ip(t,e)}});var Za=y(Xa=>{"use strict";var Ap=require("util"),Ka=require("stream"),kp=_a(),xp=Pa(),Tp=Ja(),q=Xa.PNG=function(t){Ka.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 kp(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 xp(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"))};Ap.inherits(q,Ka);q.sync=Tp;q.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)};q.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};q.prototype.write=function(t){return this._parser.write(t),!0};q.prototype.end=function(t){this._parser.end(t)};q.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};q.prototype._gamma=function(t){this.gamma=t};q.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};q.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)};q.prototype.bitblt=function(t,e,n,r,s,i,o){return q.bitblt(this,t,e,n,r,s,i,o),this};q.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}};q.prototype.adjustGamma=function(){q.adjustGamma(this)}});var Wt=y(qe=>{function Qa(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("")}}qe.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:Qa(e.color.dark||"#000000ff"),light:Qa(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};qe.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};qe.getImageWidth=function(e,n){let r=qe.getScale(e,n);return Math.floor((e+n.margin*2)*r)};qe.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=qe.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 h=Math.floor((u-l)/o),g=Math.floor((d-l)/o);p=c[i[h*s+g]?1:0]}e[f++]=p.r,e[f++]=p.g,e[f++]=p.b,e[f]=p.a}}});var el=y(le=>{var Ep=require("fs"),Cp=Za().PNG,ms=Wt();le.render=function(e,n){let r=ms.getOptions(n),s=r.rendererOpts,i=ms.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new Cp(s);return ms.qrToImageData(o.data,e,r),o};le.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),le.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};le.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=le.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()};le.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=Ep.createWriteStream(e);a.on("error",o),a.on("close",o),le.renderToFileStream(a,n,r)};le.renderToFileStream=function(e,n,r){le.render(n,r).pack().pipe(e)}});var tl=y(Nn=>{var Pp=Wt(),Rp={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Lp={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Mp(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Nn.render=function(t,e,n){let r=Pp.getOptions(e),s=Rp;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=Lp);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+=Mp(f,p,s)}a+=c+`
15
+ `}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};Nn.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=require("fs"),o=Nn.render(n,r);i.writeFile(e,o,s)}});var rl=y(nl=>{nl.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
+ `;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 r=="function"&&r(null,a),a}});var al=m(ol=>{var Mh="\x1B[47m",Nh="\x1B[40m",ys="\x1B[37m",Ss="\x1B[30m",We="\x1B[0m",Oh=Mh+Ss,Bh=Nh+ys,Dh=function(t,e,r){return{"00":We+" "+t,"01":We+e+"\u2584"+t,"02":We+r+"\u2584"+t,10:We+e+"\u2580"+t,11:" ",12:"\u2584",20:We+r+"\u2580"+t,21:"\u2580",22:"\u2588"}},sl=function(t,e,r,n){let s=e+1;if(r>=s||n>=s||n<-1||r<-1)return"0";if(r>=e||n>=e||n<0||r<0)return"1";let i=n*e+r;return t[i]?"2":"1"},il=function(t,e,r,n){return sl(t,e,r,n)+sl(t,e,r,n+1)};ol.render=function(t,e,r){let n=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?Bh:Oh,c=Dh(o,i?Ss:ys,i?ys:Ss),u=We+`
19
- `+o,d=o;for(let f=-1;f<n+1;f+=2){for(let h=-1;h<n;h++)d+=c[il(s,n,h,f)];d+=c[il(s,n,n,f)]+u}return d+=We,typeof r=="function"&&r(null,d),d}});var cl=m(ll=>{var Hh=nl(),Fh=al();ll.render=function(t,e,r){return e&&e.small?Fh.render(t,e,r):Hh.render(t,e,r)}});var vs=m(dl=>{var Uh=Wt();function ul(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function _s(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function qh(t,e,r){let n="",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]||(n+=i?_s("M",l+r,.5+c+r):_s("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(n+=_s("h",o),o=0)):s++}return n}dl.render=function(e,r,n){let s=Uh.getOptions(r),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+ul(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+ul(s.color.dark,"stroke")+' d="'+qh(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 n=="function"&&n(null,f),f}});var fl=m(Nr=>{var Wh=vs();Nr.render=Wh.render;Nr.renderToFile=function(e,r,n,s){typeof s>"u"&&(s=n,n=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">'+Nr.render(r,n);i.writeFile(e,a,s)}});var hl=m(Or=>{var ws=Wt();function jh(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function Gh(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Or.render=function(e,r,n){let s=n,i=r;typeof s>"u"&&(!r||!r.getContext)&&(s=r,r=void 0),r||(i=Gh()),s=ws.getOptions(s);let o=ws.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return ws.qrToImageData(l.data,e,s),jh(a,i,o),a.putImageData(l,0,0),i};Or.renderToDataURL=function(e,r,n){let s=n;typeof s>"u"&&(!r||!r.getContext)&&(s=r,r=void 0),s||(s={});let i=Or.render(e,r,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var gl=m(jt=>{var zh=On(),bs=es(),pl=hl(),$h=vs();function Is(t,e,r,n,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!zh())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=r,r=e,e=n=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=n,n=void 0):(s=n,n=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=n=void 0):o===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(l,c){try{let u=bs.create(r,n);l(t(u,e,n))}catch(u){c(u)}})}try{let l=bs.create(r,n);s(null,t(l,e,n))}catch(l){s(l)}}jt.create=bs.create;jt.toCanvas=Is.bind(null,pl.render);jt.toDataURL=Is.bind(null,pl.renderToDataURL);jt.toString=Is.bind(null,function(t,e,r){return $h.render(t,r)})});var _l=m(Te=>{var ml=On(),xs=es(),Vh=el(),yl=tl(),Yh=cl(),Sl=fl();function Gt(t,e,r){if(typeof t>"u")throw new Error("String required as first argument");if(typeof r>"u"&&(r=e,e={}),typeof r!="function")if(ml())e=r||{},r=null;else throw new Error("Callback required as last argument");return{opts:e,cb:r}}function Jh(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Br(t){switch(t){case"svg":return Sl;case"txt":case"utf8":return yl;case"png":case"image/png":default:return Vh}}function Kh(t){switch(t){case"svg":return Sl;case"terminal":return Yh;case"utf8":default:return yl}}function zt(t,e,r){if(!r.cb)return new Promise(function(n,s){try{let i=xs.create(e,r.opts);return t(i,r.opts,function(o,a){return o?s(o):n(a)})}catch(i){s(i)}});try{let n=xs.create(e,r.opts);return t(n,r.opts,r.cb)}catch(n){r.cb(n)}}Te.create=xs.create;Te.toCanvas=gl().toCanvas;Te.toString=function(e,r,n){let s=Gt(e,r,n),i=s.opts?s.opts.type:void 0,o=Kh(i);return zt(o.render,e,s)};Te.toDataURL=function(e,r,n){let s=Gt(e,r,n),i=Br(s.opts.type);return zt(i.renderToDataURL,e,s)};Te.toBuffer=function(e,r,n){let s=Gt(e,r,n),i=Br(s.opts.type);return zt(i.renderToBuffer,e,s)};Te.toFile=function(e,r,n,s){if(typeof e!="string"||!(typeof r=="string"||typeof r=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!ml())throw new Error("Too few arguments provided");let i=Gt(r,n,s),o=i.opts.type||Jh(e),l=Br(o).renderToFile.bind(null,e);return zt(l,r,i)};Te.toFileStream=function(e,r,n){if(arguments.length<2)throw new Error("Too few arguments provided");let s=Gt(r,n,e.emit.bind(e,"error")),o=Br("png").renderToFileStream.bind(null,e);zt(o,r,s)}});var wl=m((Ty,vl)=>{vl.exports=_l()});var Qc=require("http");var Rd=Ve(ro(),1),Ld=Ve(In(),1),Md=Ve(kn(),1),Nd=Ve(wr(),1),Nn=Ve(fo(),1);var Ge=require("fs/promises"),dn=require("path"),eu=require("os"),tu=Ve(wl(),1);var dt=require("child_process"),Nl=require("fs"),W=require("path"),Jt=require("os");var jr=require("fs");var bl=require("os"),V=require("path"),$t=(0,V.join)((0,bl.homedir)(),".vibelet"),Dr=(0,V.join)($t,"logs"),Ts=(0,V.join)($t,"data"),Xh=(0,V.join)($t,"runtime"),ky=(0,V.join)(Xh,"current"),Il=(0,V.join)($t,"identity.json"),xl=(0,V.join)($t,"pairings.json"),Tl=(0,V.join)(Ts,"push-subscriptions.json"),Hr=(0,V.join)(Ts,"sessions.json"),ct=(0,V.join)(Ts,"audit.jsonl"),Fr=(0,V.join)(Dr,"daemon.stdout.log"),Ur=(0,V.join)(Dr,"daemon.stderr.log");var qr={stdout:!1,stderr:!1};function kl(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function Zh(t){return!t.destroyed&&t.writable!==!1}function El(t,e){if(qr[t])return!1;let r=t==="stderr"?process.stderr:process.stdout;if(!Zh(r))return qr[t]=!0,!1;try{return r.write(e,n=>{kl(n)&&(qr[t]=!0)}),!0}catch(n){return kl(n)&&(qr[t]=!0),!1}}function Vt(t){return El("stdout",t)}function Wr(t){return El("stderr",t)}var Al={debug:10,info:20,warn:30,error:40},Qh=process.env.VIBE_LOG_LEVEL||"info";function ep(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}var Pl=!ep();if(Pl)try{(0,jr.mkdirSync)(Dr,{recursive:!0})}catch{}function Cl(t,e,r){if(Al[t]<Al[Qh])return;let n={level:t,ts:new Date().toISOString(),msg:r,...e},s=JSON.stringify(n);if(t==="error"||t==="warn"?Wr(s+`
18
+ `,typeof n=="function"&&n(null,a),a}});var al=y(ol=>{var Np="\x1B[47m",Op="\x1B[40m",ys="\x1B[37m",Ss="\x1B[30m",We="\x1B[0m",Bp=Np+Ss,Dp=Op+ys,Hp=function(t,e,n){return{"00":We+" "+t,"01":We+e+"\u2584"+t,"02":We+n+"\u2584"+t,10:We+e+"\u2580"+t,11:" ",12:"\u2584",20:We+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},sl=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"},il=function(t,e,n,r){return sl(t,e,n,r)+sl(t,e,n,r+1)};ol.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?Dp:Bp,c=Hp(o,i?Ss:ys,i?ys:Ss),u=We+`
19
+ `+o,d=o;for(let f=-1;f<r+1;f+=2){for(let p=-1;p<r;p++)d+=c[il(s,r,p,f)];d+=c[il(s,r,r,f)]+u}return d+=We,typeof n=="function"&&n(null,d),d}});var cl=y(ll=>{var Fp=rl(),Up=al();ll.render=function(t,e,n){return e&&e.small?Up.render(t,e,n):Fp.render(t,e,n)}});var _s=y(dl=>{var qp=Wt();function ul(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function vs(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function Wp(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?vs("M",l+n,.5+c+n):vs("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=vs("h",o),o=0)):s++}return r}dl.render=function(e,n,r){let s=qp.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+ul(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+ul(s.color.dark,"stroke")+' d="'+Wp(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 fl=y(On=>{var jp=_s();On.render=jp.render;On.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">'+On.render(n,r);i.writeFile(e,a,s)}});var pl=y(Bn=>{var ws=Wt();function Gp(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 $p(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Bn.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=$p()),s=ws.getOptions(s);let o=ws.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return ws.qrToImageData(l.data,e,s),Gp(a,i,o),a.putImageData(l,0,0),i};Bn.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=Bn.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var gl=y(jt=>{var zp=Or(),bs=es(),hl=pl(),Vp=_s();function Is(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!zp())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=bs.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=bs.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}jt.create=bs.create;jt.toCanvas=Is.bind(null,hl.render);jt.toDataURL=Is.bind(null,hl.renderToDataURL);jt.toString=Is.bind(null,function(t,e,n){return Vp.render(t,n)})});var vl=y(ke=>{var ml=Or(),As=es(),Yp=el(),yl=tl(),Jp=cl(),Sl=fl();function Gt(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(ml())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function Kp(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Dn(t){switch(t){case"svg":return Sl;case"txt":case"utf8":return yl;case"png":case"image/png":default:return Yp}}function Xp(t){switch(t){case"svg":return Sl;case"terminal":return Jp;case"utf8":default:return yl}}function $t(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=As.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=As.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}ke.create=As.create;ke.toCanvas=gl().toCanvas;ke.toString=function(e,n,r){let s=Gt(e,n,r),i=s.opts?s.opts.type:void 0,o=Xp(i);return $t(o.render,e,s)};ke.toDataURL=function(e,n,r){let s=Gt(e,n,r),i=Dn(s.opts.type);return $t(i.renderToDataURL,e,s)};ke.toBuffer=function(e,n,r){let s=Gt(e,n,r),i=Dn(s.opts.type);return $t(i.renderToBuffer,e,s)};ke.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&&!ml())throw new Error("Too few arguments provided");let i=Gt(n,r,s),o=i.opts.type||Kp(e),l=Dn(o).renderToFile.bind(null,e);return $t(l,n,i)};ke.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=Gt(n,r,e.emit.bind(e,"error")),o=Dn("png").renderToFileStream.bind(null,e);$t(o,n,s)}});var wl=y((Py,_l)=>{_l.exports=vl()});var eu=require("http");var Ld=Ve(no(),1),Md=Ve(Ir(),1),Nd=Ve(xr(),1),Od=Ve(bn(),1),Nr=Ve(fo(),1);var Ge=require("fs/promises"),dr=require("path"),tu=require("os"),nu=Ve(wl(),1);var dt=require("child_process"),Nl=require("fs"),W=require("path"),Jt=require("os");var Gn=require("fs");var bl=require("os"),V=require("path"),zt=(0,V.join)((0,bl.homedir)(),".vibelet"),Hn=(0,V.join)(zt,"logs"),ks=(0,V.join)(zt,"data"),Zp=(0,V.join)(zt,"runtime"),Ry=(0,V.join)(Zp,"current"),Il=(0,V.join)(zt,"identity.json"),Al=(0,V.join)(zt,"pairings.json"),kl=(0,V.join)(ks,"push-subscriptions.json"),Fn=(0,V.join)(ks,"sessions.json"),ct=(0,V.join)(ks,"audit.jsonl"),Un=(0,V.join)(Hn,"daemon.stdout.log"),qn=(0,V.join)(Hn,"daemon.stderr.log");var Wn={stdout:!1,stderr:!1};function xl(t){if(!t||typeof t!="object")return!1;let e=typeof t.code=="string"?t.code:"";return e==="EIO"||e==="EPIPE"}function Qp(t){return!t.destroyed&&t.writable!==!1}function Tl(t,e){if(Wn[t])return!1;let n=t==="stderr"?process.stderr:process.stdout;if(!Qp(n))return Wn[t]=!0,!1;try{return n.write(e,r=>{xl(r)&&(Wn[t]=!0)}),!0}catch(r){return xl(r)&&(Wn[t]=!0),!1}}function Vt(t){return Tl("stdout",t)}function jn(t){return Tl("stderr",t)}var El={debug:10,info:20,warn:30,error:40},eh=process.env.VIBE_LOG_LEVEL||"info";function th(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}var Pl=!th();if(Pl)try{(0,Gn.mkdirSync)(Hn,{recursive:!0})}catch{}function Cl(t,e,n){if(El[t]<El[eh])return;let r={level:t,ts:new Date().toISOString(),msg:n,...e},s=JSON.stringify(r);if(t==="error"||t==="warn"?jn(s+`
21
21
  `):Vt(s+`
22
- `),Pl){let i=t==="error"||t==="warn"?Ur:Fr;try{(0,jr.appendFileSync)(i,s+`
23
- `)}catch{}}}function Rl(t={}){function e(r,n,s){typeof n=="string"?Cl(r,t,n):Cl(r,{...t,...n},s)}return{debug:(r,n)=>e("debug",r,n),info:(r,n)=>e("info",r,n),warn:(r,n)=>e("warn",r,n),error:(r,n)=>e("error",r,n),child:r=>Rl({...t,...r})}}var L=Rl({module:"daemon"});var tp=["fnm_multishells"],rp=6e4,np=L.child({module:"config"});function ke(t){return tp.some(e=>t.includes(e))}function Es(){return[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,r)=>r.indexOf(t)===e)}var ut=null;function Ol(){if(ut&&!ke(ut.PATH??""))return ut;for(let t of Es())try{let e=(0,dt.execFileSync)(t,["-ilc","env"],{timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),r={};for(let n of e.split(`
24
- `)){let s=n.indexOf("=");s>0&&(r[n.slice(0,s)]=n.slice(s+1))}return ke(r.PATH??"")?ut=null:ut=r,r}catch{}return ut={},{}}function sp(t=Ol()){let e=(0,Jt.homedir)(),r=t.PNPM_HOME||process.env.PNPM_HOME||(0,W.join)(e,"Library","pnpm"),n=t.PATH||process.env.PATH||"",s=["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,W.join)(e,".npm-global","bin"),(0,W.join)(e,".local","bin"),(0,W.join)(e,".claude","bin"),r],i=n.split(W.delimiter).filter(Boolean),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(W.delimiter)}function ks(t,e){let r=process.env[t];if(!r)return e;let n=Number(r);return Number.isFinite(n)&&n>0?Math.floor(n):e}function Ll(t,e){let r=process.env[t];if(r==null||r==="")return e;let n=Number(r);return Number.isFinite(n)&&n>=0?Math.floor(n):e}function Gr(){let t=Ol(),e={};for(let[r,n]of Object.entries(process.env))typeof n=="string"&&(e[r]=n);for(let[r,n]of Object.entries(t))typeof n=="string"&&(e[r]=n);return e.PATH=sp(t),e.HOME||(e.HOME=(0,Jt.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Yt(t,e=3e3){try{return(0,dt.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:Gr()}).trim()||null}catch{return null}}function ip(t){for(let e of Es())try{let r=(0,dt.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(r)return r}catch{}}function op(){let t=(0,Jt.homedir)();return[(0,W.join)(t,".local","bin","claude"),(0,W.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,W.join)(t,".npm-global","bin","claude")]}function ap(){for(let t of op())if(Yt(t))return t;try{let t=(0,dt.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Gr()}).trim();if(t&&!t.includes("cmux")&&Yt(t))return t}catch{}}function lp(){let t=(0,Jt.homedir)(),e=[process.env.PNPM_HOME,(0,W.join)(t,"Library","pnpm")].filter(r=>!!r);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,W.join)(t,".npm-global","bin","codex"),(0,W.join)(t,".local","bin","codex"),...e.map(r=>(0,W.join)(r,"codex"))]}function cp(){let t;for(let r of lp())if(Yt(r)){if(!ke(r))return r;t=r}try{let r=(0,dt.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:Gr()}).trim();if(r&&Yt(r)){if(!ke(r))return r;t=t??r}}catch{}let e=ip("codex");if(e&&Yt(e)){if(!ke(e))return e;t=t??e}return t}function Bl(t,e){let r=null,n=0;return()=>{let s=e==="claude"?"CLAUDE_PATH":"CODEX_PATH";if(process.env[s])return process.env[s];let i=Date.now();return(!r||i-n>rp||!(0,Nl.existsSync)(r)||ke(r))&&(r=t()??e,n=i,np.info({name:e,path:r,transient:ke(r)},"binary resolved")),r}}var up=Bl(ap,"claude"),dp=Bl(cp,"codex");function fp(){let t={},e=process.argv.slice(2);for(let r=0;r<e.length;r++){let n=e[r];if(n.startsWith("--")&&r+1<e.length){let s=n.slice(2);t[s]=e[++r]}}return t}var Ml=fp();function hp(t,e){return{command:Es()[0]??"/bin/zsh",args:["-lc",`command -v ${t} >/dev/null 2>&1 && exec ${t} "$@"`,"--",...e]}}var _={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:Ml.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:Ml["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:Ll("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:Ll("VIBE_TURN_STALL_TIMEOUT_MS",300*1e3),auditMaxBytes:ks("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:ks("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:ks("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),get claudePath(){return up()},get codexPath(){return dp()},isTransientPath:ke,execViaLoginShell:hp,buildSanitizedEnv:Gr};var Xs=require("crypto"),Mc=require("fs/promises");var zl=require("child_process"),$l=require("fs");var zr=require("fs"),Fl=require("path");var G=require("fs");function pp(t,e,r,n){let s=Math.max(0,e-r),i=Math.floor(e*.75);return Math.max(0,Math.min(t,s,n??i))}function Kt(t,e){if(!(0,G.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let n=(0,G.statSync)(t).size,s=Math.max(0,e.incomingBytes??0);if(e.maxBytes<=0||n+s<=e.maxBytes)return{path:t,existed:!0,trimmed:!1,beforeBytes:n,afterBytes:n,reclaimedBytes:0};let i=pp(n,e.maxBytes,s,e.retainBytes),o=(0,G.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,G.readSync)(o,l,0,i,n-i);let c=0;if(n>i){let u=l.indexOf(10);u>=0&&u+1<l.length&&(c=u+1)}a=l.subarray(c)}return(0,G.ftruncateSync)(o,0),a.length>0&&(0,G.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:n,afterBytes:a.length,reclaimedBytes:n-a.length}}finally{(0,G.closeSync)(o)}}function Dl(t){let e=[Kt(t.auditPath,{maxBytes:t.auditMaxBytes}),Kt(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),Kt(t.stderrLogPath,{maxBytes:t.logMaxBytes})];return{files:e,trimmedFiles:e.filter(r=>r.trimmed).length,reclaimedBytes:e.reduce((r,n)=>r+n.reclaimedBytes,0)}}var Hl=!1,gp=new Set(["ts","event","source","appEvent","level"]);function mp(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function yp(t={}){let e={};for(let[r,n]of Object.entries(t))gp.has(r)||(e[r]=n);return e}function Sp(t,e,r={},n){return{ts:n??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...yp(r)}}function _p(){Hl||((0,zr.mkdirSync)((0,Fl.dirname)(ct),{recursive:!0}),Hl=!0)}var As=class{emit(e,r={}){this.write({ts:new Date().toISOString(),event:e,...r})}emitApp(e,r,n={},s){this.write(Sp(e,r,n,s))}write(e){if(!mp()){_p();try{let r=JSON.stringify(e)+`
25
- `;Kt(ct,{maxBytes:_.auditMaxBytes,incomingBytes:Buffer.byteLength(r)}),(0,zr.appendFileSync)(ct,r)}catch{}}}},w=new As;var Ee=require("fs"),Ul=require("os"),Xt=require("path"),ql=require("crypto"),Cs="claude-hook:",Zt="x-vibelet-claude-hook-secret",Qt={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function vp(t,e){return`#!/usr/bin/env node
22
+ `),Pl){let i=t==="error"||t==="warn"?qn:Un;try{(0,Gn.appendFileSync)(i,s+`
23
+ `)}catch{}}}function Rl(t={}){function e(n,r,s){typeof r=="string"?Cl(n,t,r):Cl(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=>Rl({...t,...n})}}var L=Rl({module:"daemon"});var nh=["fnm_multishells"],rh=6e4,sh=L.child({module:"config"});function xe(t){return nh.some(e=>t.includes(e))}function Ts(){return[process.env.SHELL,"/bin/zsh","/bin/bash","/bin/sh"].filter(t=>!!t).filter((t,e,n)=>n.indexOf(t)===e)}var ut=null;function Ol(){if(ut&&!xe(ut.PATH??""))return ut;for(let t of Ts())try{let e=(0,dt.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 xe(n.PATH??"")?ut=null:ut=n,n}catch{}return ut={},{}}function ih(t=Ol()){let e=(0,Jt.homedir)(),n=t.PNPM_HOME||process.env.PNPM_HOME||(0,W.join)(e,"Library","pnpm"),r=t.PATH||process.env.PATH||"",s=["/usr/local/bin","/opt/homebrew/bin","/usr/bin","/bin",(0,W.join)(e,".npm-global","bin"),(0,W.join)(e,".local","bin"),(0,W.join)(e,".claude","bin"),n],i=r.split(W.delimiter).filter(Boolean),o=new Set(i);for(let a of s)o.has(a)||(i.push(a),o.add(a));return i.join(W.delimiter)}function xs(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 Ll(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 $n(){let t=Ol(),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=ih(t),e.HOME||(e.HOME=(0,Jt.homedir)()),delete e.CLAUDE_CODE_ENTRYPOINT,delete e.CLAUDECODE,e}function Yt(t,e=3e3){try{return(0,dt.execFileSync)(t,["--version"],{timeout:e,stdio:"pipe",encoding:"utf-8",env:$n()}).trim()||null}catch{return null}}function oh(t){for(let e of Ts())try{let n=(0,dt.execFileSync)(e,["-ilc",`command -v ${t}`],{timeout:5e3,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim();if(n)return n}catch{}}function ah(){let t=(0,Jt.homedir)();return[(0,W.join)(t,".local","bin","claude"),(0,W.join)(t,".claude","bin","claude"),"/usr/local/bin/claude","/opt/homebrew/bin/claude",(0,W.join)(t,".npm-global","bin","claude")]}function lh(){for(let t of ah())if(Yt(t))return t;try{let t=(0,dt.execFileSync)("/usr/bin/which",["claude"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:$n()}).trim();if(t&&!t.includes("cmux")&&Yt(t))return t}catch{}}function ch(){let t=(0,Jt.homedir)(),e=[process.env.PNPM_HOME,(0,W.join)(t,"Library","pnpm")].filter(n=>!!n);return["/usr/local/bin/codex","/opt/homebrew/bin/codex",(0,W.join)(t,".npm-global","bin","codex"),(0,W.join)(t,".local","bin","codex"),...e.map(n=>(0,W.join)(n,"codex"))]}function uh(){let t;for(let n of ch())if(Yt(n)){if(!xe(n))return n;t=n}try{let n=(0,dt.execFileSync)("/usr/bin/which",["codex"],{timeout:3e3,stdio:"pipe",encoding:"utf-8",env:$n()}).trim();if(n&&Yt(n)){if(!xe(n))return n;t=t??n}}catch{}let e=oh("codex");if(e&&Yt(e)){if(!xe(e))return e;t=t??e}return t}function Bl(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();return(!n||i-r>rh||!(0,Nl.existsSync)(n)||xe(n))&&(n=t()??e,r=i,sh.info({name:e,path:n,transient:xe(n)},"binary resolved")),n}}var dh=Bl(lh,"claude"),fh=Bl(uh,"codex");function ph(){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 Ml=ph();function hh(t,e){return{command:Ts()[0]??"/bin/zsh",args:["-lc",`command -v ${t} >/dev/null 2>&1 && exec ${t} "$@"`,"--",...e]}}var v={port:Number(process.env.VIBE_PORT)||9876,legacyToken:process.env.VIBE_TOKEN||"",canonicalHost:Ml.host||process.env.VIBELET_CANONICAL_HOST||process.env.VIBELET_HOST||"",fallbackHosts:Ml["fallback-hosts"]||process.env.VIBELET_FALLBACK_HOSTS||"",relayUrl:process.env.VIBELET_RELAY_URL||"",idleTimeoutMs:Ll("VIBE_IDLE_TIMEOUT_MS",1800*1e3),turnStallTimeoutMs:Ll("VIBE_TURN_STALL_TIMEOUT_MS",300*1e3),auditMaxBytes:xs("VIBE_AUDIT_MAX_BYTES",8*1024*1024),daemonLogMaxBytes:xs("VIBE_DAEMON_LOG_MAX_BYTES",16*1024*1024),storageHousekeepingIntervalMs:xs("VIBE_STORAGE_HOUSEKEEPING_INTERVAL_MS",300*1e3),get claudePath(){return dh()},get codexPath(){return fh()},isTransientPath:xe,execViaLoginShell:hh,buildSanitizedEnv:$n};var Xs=require("crypto"),Nc=require("fs/promises");var $l=require("child_process"),zl=require("fs");var zn=require("fs"),Fl=require("path");var G=require("fs");function gh(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 Kt(t,e){if(!(0,G.existsSync)(t))return{path:t,existed:!1,trimmed:!1,beforeBytes:0,afterBytes:0,reclaimedBytes:0};let r=(0,G.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=gh(r,e.maxBytes,s,e.retainBytes),o=(0,G.openSync)(t,"r+");try{let a=Buffer.alloc(0);if(i>0){let l=Buffer.alloc(i);(0,G.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,G.ftruncateSync)(o,0),a.length>0&&(0,G.writeSync)(o,a,0,a.length,0),{path:t,existed:!0,trimmed:!0,beforeBytes:r,afterBytes:a.length,reclaimedBytes:r-a.length}}finally{(0,G.closeSync)(o)}}function Dl(t){let e=[Kt(t.auditPath,{maxBytes:t.auditMaxBytes}),Kt(t.stdoutLogPath,{maxBytes:t.logMaxBytes}),Kt(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 Hl=!1,mh=new Set(["ts","event","source","appEvent","level"]);function yh(){return process.env.VIBE_TEST==="1"||process.argv.includes("--test")}function Sh(t={}){let e={};for(let[n,r]of Object.entries(t))mh.has(n)||(e[n]=r);return e}function vh(t,e,n={},r){return{ts:r??new Date().toISOString(),event:"app.log",source:"app",appEvent:t,level:e,...Sh(n)}}function _h(){Hl||((0,zn.mkdirSync)((0,Fl.dirname)(ct),{recursive:!0}),Hl=!0)}var Es=class{emit(e,n={}){this.write({ts:new Date().toISOString(),event:e,...n})}emitApp(e,n,r={},s){this.write(vh(e,n,r,s))}write(e){if(!yh()){_h();try{let n=JSON.stringify(e)+`
25
+ `;Kt(ct,{maxBytes:v.auditMaxBytes,incomingBytes:Buffer.byteLength(n)}),(0,zn.appendFileSync)(ct,n)}catch{}}}},w=new Es;var Te=require("fs"),Ul=require("os"),Xt=require("path"),ql=require("crypto"),Cs="claude-hook:",Zt="x-vibelet-claude-hook-secret",Qt={continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"PreToolUse"}};function wh(t,e){return`#!/usr/bin/env node
26
26
  const http = require('http');
27
27
  const chunks = [];
28
28
  process.stdin.on('data', (chunk) => chunks.push(chunk));
@@ -43,7 +43,7 @@ process.stdin.on('end', () => {
43
43
  req.end(body);
44
44
  });
45
45
  process.stdin.resume();
46
- `}function wp(t,e){return`#!/usr/bin/env node
46
+ `}function bh(t,e){return`#!/usr/bin/env node
47
47
  const http = require('http');
48
48
  const fallback = ${JSON.stringify(JSON.stringify(Qt))};
49
49
  const chunks = [];
@@ -79,29 +79,29 @@ process.stdin.on('end', () => {
79
79
  req.end(body);
80
80
  });
81
81
  process.stdin.resume();
82
- `}function Wl(t,e){let r=(0,Xt.join)((0,Ul.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,ql.randomUUID)()}`);(0,Ee.mkdirSync)(r,{recursive:!0});let n=(0,Xt.join)(r,"settings.json"),s=(0,Xt.join)(r,"session_hook_forwarder.cjs"),i=(0,Xt.join)(r,"permission_hook_forwarder.cjs");return(0,Ee.writeFileSync)(s,vp(t,e),"utf8"),(0,Ee.writeFileSync)(i,wp(t,e),"utf8"),(0,Ee.writeFileSync)(n,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:r,settingsPath:n,sessionScriptPath:s,permissionScriptPath:i}}function $r(t){if(t)try{(0,Ee.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var Q=L.child({module:"claude"}),Vl="claude-permission-denial:",bp=/\u001B\[[0-?]*[ -/]*[@-~]/g;function Ip(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function Ps(t){Ip()&&Wr(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
83
- `)}function xp(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 Tp(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function kp(t){if(typeof t=="string")return t;let e=xp(t);return e||(Tp(t)?"":JSON.stringify(t))}function Ep(t){return/requested permissions|haven't granted/i.test(t)}function jl(t){return t.replace(bp,"").replace(/\s+/g," ").trim()}function Ap(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function Cp(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 Pp(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Gl(t){let e=jl(t.resultText??""),r=(t.stderrLines??[]).map(jl).filter(Boolean).slice(-3),n=[e,...r].find(i=>!!i&&Cp(i));if(n)return Pp(n);let s=[e,...r].find(i=>!!i&&!Ap(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 Vr(t){return t.startsWith(Vl)}var er=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=_.buildSanitizedEnv();for(let r of Object.keys(e))r.startsWith("CMUX_")&&delete e[r];return e}async start(e,r,n){return this.cwd=e,this.approvalMode=n,r&&(this.sessionId=r),this.sessionId||(this.sessionId=`pending_${Date.now()}`),Q.info({sessionId:this.sessionId,cwd:e},"session initialized"),w.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,r){this.hookPort=e,this.hookSecret=r}sendPrompt(e){let r=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];this.sessionId&&!this.sessionId.startsWith("pending_")&&r.push("--resume",this.sessionId),$r(this.hookFiles),this.hookFiles=null,this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=Wl(this.hookPort,this.hookSecret),r.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="acceptEdits"&&r.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&r.push("--dangerously-skip-permissions");let n=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;Q.info({sessionId:this.sessionId,label:n,promptPreview:e.slice(0,50)},"running claude"),Ps(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.replayPhase=!0,this.proc=(0,zl.spawn)(_.claudePath,r,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv()}),this.proc.on("error",s=>{let i=s.message;s.code==="ENOENT"&&this.cwd&&!(0,$l.existsSync)(this.cwd)&&(i=`Working directory does not exist: ${this.cwd}`),Q.error({sessionId:this.sessionId,error:i,cwd:this.cwd},"spawn error"),w.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:i}),this.handler?.({type:"error",sessionId:this.sessionId,message:i})}),this.buffer="",this.proc.stdout.on("data",s=>{this.buffer+=s.toString();let i=this.buffer.split(`
85
- `);this.buffer=i.pop();for(let o of i)if(o.trim())try{this.handleRaw(JSON.parse(o))}catch{Q.warn({sessionId:this.sessionId,linePreview:o.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",s=>{let i=s.toString().trim();i&&(Q.debug({sessionId:this.sessionId,stderr:i},"stderr"),this.lastStderr.push(i),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(s,i)=>{Q.info({sessionId:this.sessionId,exitCode:s,signal:i},"process exited");let o=this.interrupted;this.proc=null,$r(this.hookFiles),this.hookFiles=null,this.interrupted=!1,o&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):s&&s!==0&&!this.sawFinalResult&&(Q.error({sessionId:this.sessionId,exitCode:s,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Gl({stderrLines:this.lastStderr,exitCode:s})})),this.exitHandler?.(s)})}respondApproval(e,r){if(Q.info({sessionId:this.sessionId,requestId:e,approved:r},"approval response"),!this.proc?.stdin?.writable)return Q.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let n=JSON.stringify({type:"control_response",request_id:e,permission_granted:r});return this.proc.stdin.write(n+`
86
- `),!0}setApprovalMode(e){this.approvalMode=e,Q.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),Q.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,$r(this.hookFiles),this.hookFiles=null}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let r=e.type;if(r==="system"&&e.subtype==="init"){let n=e.session_id??"";n&&n!==this.sessionId&&(Q.info({oldSessionId:this.sessionId,newSessionId:n},"session ID resolved"),w.emit("driver.init",{agent:"claude",sessionId:n}),this.sessionId=n);return}if(this.handler)switch(r){case"assistant":{if(this.replayPhase)break;let n=e.message?.content;if(!Array.isArray(n))break;for(let s of n)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 n=e.message?.content;if(!Array.isArray(n))break;for(let s of n)if(s.type==="tool_result"){let i=kp(s.content);if(!i)continue;if(s.is_error===!0&&typeof s.tool_use_id=="string"&&Ep(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 n=e.request;n?.subtype==="can_use_tool"&&(w.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:n.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:n.tool_name??"unknown",input:n.input??{},description:n.description??n.title??""}));break}case"stream_event":{this.replayPhase=!1;let n=e.event;n?.type==="content_block_delta"&&n?.delta?.type==="text_delta"&&n?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:n.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let n=typeof e.result=="string"?e.result:"";if(e.is_error){Ps("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Gl({resultText:n,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}.`;w.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:c}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${Vl}${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;Ps("Claude finished. Run `claude --continue` to continue on desktop."),w.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 Xl=require("child_process"),Zl=require("fs");var Rs=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,r={}){this.counters.has(e)||this.counters.set(e,[]);let n=this.counters.get(e),s=JSON.stringify(r),i=n.find(o=>JSON.stringify(o.labels)===s);i?i.value++:n.push({value:1,labels:r})}gauge(e,r){this.gauges.set(e,r)}startTimer(e){let r=performance.now();return()=>{let n=Math.round(performance.now()-r),s=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return s.count++,s.totalMs+=n,s.minMs=Math.min(s.minMs,n),s.maxMs=Math.max(s.maxMs,n),s.lastMs=n,this.timers.set(e,s),n}}snapshot(){let e={};for(let[s,i]of this.counters)e[s]=i.map(o=>({...o}));let r={};for(let[s,i]of this.timers)r[s]={...i,minMs:i.minMs===1/0?0:i.minMs};let n={};for(let[s,i]of this.gauges)n[s]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:r,gauges:n}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let r=this.snapshot();L.info({metrics:r},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},b=new Rs;var Yl=require("node:fs"),Ls=require("node:path"),Rp="@vibelet/cli";function Lp(t){try{let e=JSON.parse((0,Yl.readFileSync)(t,"utf8"));if(e.name===Rp&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function Mp(){return"0.1.4"}var ft=Mp();var k=L.child({module:"codex"});function ee(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function C(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function Np(t){let e=C(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function Ms(t){return t?C(t.itemId)??C(t.id)??C(t.callId)??C(t.call_id):null}function Ns(t,e){let r={};for(let[n,s]of Object.entries(t))e.includes(n)||(r[n]=s);return r}function Ql(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function ec(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function Op(t){if(!Array.isArray(t))return null;for(let e of t){let r=ee(e);if(!r)continue;let n=C(r.id),s=Array.isArray(r.options)?r.options.map(l=>ee(l)).filter(l=>!!l):[];if(!n||s.length===0)continue;let i=s.map(l=>C(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>Ql(l))??i[0],a=i.find(l=>ec(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:n,approveLabel:o,denyLabel:a}}return null}function Bp(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(s=>ee(s)).filter(s=>!!s).flatMap(s=>(Array.isArray(s.options)?s.options:[]).map(o=>ee(o)).filter(o=>!!o).map(o=>C(o.label)).filter(o=>!!o)),r=e.some(s=>Ql(s)),n=e.some(s=>ec(s));return r&&n}function Jl(t){let e=Np(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:Ns(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:Ns(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let r=C(t.server),n=C(t.tool)??C(t.name);return n?{toolName:r?`mcp__${r}__${n}`:n,input:ee(t.arguments)??ee(t.input)??{}}:null}return null}function Dp(t){if(!Array.isArray(t))return"";for(let e of t){let r=ee(e);if(!r)continue;let n=C(r.question)??C(r.header);if(n)return n}return""}function Kl(t,e){return t==="autoApprove"?{approvalPolicy:"never",sandbox:"danger-full-access",sandboxPolicy:{type:"dangerFullAccess"}}:{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[e],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}}var Yr=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;approvalMode;cwd="";async start(e,r,n){this.approvalMode=n,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear();let s=_.codexPath,i,o=this.buildSpawnArgs();if(_.isTransientPath(s)){let c=_.execViaLoginShell("codex",o);i=c.command,o=c.args,k.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=s,k.info({spawnCmd:i,args:o},"spawning");w.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:r}),this.lastStderr=[],this.proc=(0,Xl.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:_.buildSanitizedEnv()}),this.proc.on("error",c=>{let u=c.message;c.code==="ENOENT"&&e&&!(0,Zl.existsSync)(e)&&(u=`Working directory does not exist: ${e}`),k.error({error:u,cwd:e},"spawn error"),w.emit("driver.error",{agent:"codex",error:u})}),this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let u=this.buffer.split(`
87
- `);this.buffer=u.pop();for(let d of u)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{k.warn({linePreview:d.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let u=c.toString().trim();u&&(k.debug({stderr:u},"stderr"),this.lastStderr.push(u),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{k.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&k.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear();for(let[,{reject:u}]of this.pending)u(new Error(`Codex process exited with code ${c}`));this.pending.clear(),this.exitHandler?.(c),c&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${c}`})});let a=b.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:ft},capabilities:{experimentalApi:!0}}),a(),this.rpcNotify("initialized",{});let l=Kl(this.approvalMode,e);if(r){let c=await this.rpc("thread/resume",{threadId:r,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,persistExtendedHistory:!0});this.threadId=c?.thread?.id??r,k.info({threadId:this.threadId},"thread resumed"),w.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let c=await this.rpc("thread/start",{cwd:e,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=c?.thread?.id??c?.threadId??"",k.info({threadId:this.threadId},"thread created"),w.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}buildSpawnArgs(){return["app-server","--listen","stdio://"]}sendPrompt(e){let r=Kl(this.approvalMode,this.cwd||process.cwd());k.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(n=>k.debug({resultPreview:JSON.stringify(n).slice(0,200)},"turn/start result")).catch(n=>{k.error({threadId:this.threadId,error:n.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:n.message})})}respondApproval(e,r){if(!this.proc?.stdin?.writable)return!1;let n=this.approvalRequests.get(e),s=n?.rpcId??Number(e);if(!Number.isFinite(s))return!1;let i;if(!n)i=r?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(n.kind){case"command-execution":case"file-change":i={decision:r?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[n.questionId]:{answers:[r?n.approveLabel:n.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:r?"approved":"denied"};break;default:i={decision:r?"accept":"decline"};break}this.approvalRequests.delete(e)}return k.info({threadId:this.threadId,rpcId:s,approved:r},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,result:i})+`
88
- `),!0}interrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}setApprovalMode(e){this.approvalMode=e,k.info({approvalMode:e},"approval mode updated (takes effect on restart)")}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();for(let[,{reject:r}]of this.pending)r(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,r){let n=++this.rpcId,s=b.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(n,{resolve:a=>{s(),i(a)},reject:a=>{s(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(n),s(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:n,params:r})+`
89
- `),setTimeout(()=>{this.pending.has(n)&&(this.pending.delete(n),k.error({method:e,rpcId:n,threadId:this.threadId},"RPC timeout"),s(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}rpcNotify(e,r){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:r})+`
90
- `)}writeServerRequestError(e,r){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:e,error:{code:-32601,message:r}})+`
91
- `)}resolveToolContext(e){let r=ee(e?.item)??e??null,n=Ms(r);if(!n)return null;let s=r?Jl(r):null;if(s)return this.toolContextByCallId.set(n,s),{callId:n,toolContext:s};let i=this.toolContextByCallId.get(n);return i?{callId:n,toolContext:i}:null}createFallbackInput(e,r){return e?Ns(e,["threadId","turnId",...r]):{}}queueApprovalRequest(e,r,n){if(this.approvalRequests.set(e,r),w.emit("approval.request",{agent:"codex",sessionId:this.threadId,toolName:r.toolName}),!this.handler){k.warn({threadId:this.threadId,requestId:e,toolName:r.toolName},"approval request received without handler"),this.respondApproval(e,!1)||this.writeServerRequestError(r.rpcId,"Approval handler unavailable");return}this.handler({type:"approval.request",sessionId:this.threadId,requestId:e,toolName:r.toolName,input:r.input,description:n})}handleServerRequest(e,r,n){let s=String(r),i=this.resolveToolContext(n);if(e==="item/commandExecution/requestApproval"){this.queueApprovalRequest(s,{kind:"command-execution",responseKind:"v2",rpcId:r,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(n,["itemId","reason","description"])},C(n?.reason)??C(n?.description)??"");return}if(e==="item/fileChange/requestApproval"){this.queueApprovalRequest(s,{kind:"file-change",responseKind:"v2",rpcId:r,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(n,["itemId","reason","description"])},C(n?.reason)??C(n?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=n?.questions;if(!Bp(o)){k.warn({threadId:this.threadId,rpcId:r},"unsupported requestUserInput request"),this.writeServerRequestError(r,"Unsupported interactive request from Codex");return}let a=Op(o);if(!a){this.writeServerRequestError(r,"Malformed requestUserInput approval request");return}this.queueApprovalRequest(s,{kind:"request-user-input-approval",rpcId:r,questionId:a.questionId,approveLabel:a.approveLabel,denyLabel:a.denyLabel,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(n,["itemId","questions"])},Dp(o));return}if(e==="execCommandApproval"){this.queueApprovalRequest(s,{kind:"exec-command-legacy",rpcId:r,toolName:i?.toolContext.toolName??"Bash",input:i?.toolContext.input??this.createFallbackInput(n,[])},C(n?.reason)??C(n?.description)??"");return}if(e==="applyPatchApproval"){this.queueApprovalRequest(s,{kind:"apply-patch-legacy",rpcId:r,toolName:i?.toolContext.toolName??"Patch",input:i?.toolContext.input??this.createFallbackInput(n,[])},C(n?.reason)??C(n?.description)??"");return}if(e==="item/permissions/requestApproval"){k.warn({threadId:this.threadId,rpcId:r},"unsupported permissions approval request"),this.writeServerRequestError(r,"Unsupported permissions approval request");return}k.warn({threadId:this.threadId,rpcId:r,method:e},"unsupported server request"),this.writeServerRequestError(r,`Unsupported server request: ${e}`)}handleRaw(e){if(k.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 r=typeof e.method=="string"?e.method:void 0,n=ee(e.params);if(r&&e.id!=null){this.handleServerRequest(r,e.id,n??void 0);return}switch(r&&k.debug({method:r,paramsPreview:JSON.stringify(n??{}).slice(0,300)},"notification"),r){case"item/agentMessage/delta":{let s=n?.text??n?.delta??n?.content??"";s&&this.handler?this.handler({type:"text.delta",sessionId:this.threadId,content:s}):s||k.debug({paramsKeys:Object.keys(n??{})},"agentMessage/delta with empty text");break}case"item/commandExecution/outputDelta":n?.output&&this.handler&&this.handler({type:"tool.result",sessionId:this.threadId,toolCallId:n.itemId??"",output:String(n.output)});break;case"item/started":{let s=ee(n?.item),i=Ms(s),o=s?Jl(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=ee(n?.item)??n,i=Ms(s);i&&this.toolContextByCallId.delete(i);break}case"turn/completed":{let s=ee(n?.usage),i=s?{inputTokens:Number(s.input_tokens??s.inputTokens??0),outputTokens:Number(s.output_tokens??s.outputTokens??0)}:void 0;k.info({threadId:this.threadId},"turn completed"),w.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:i}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:i});break}default:r&&k.debug({method:r},"unhandled notification");break}}};var B=require("fs/promises"),Gs=require("fs"),zs=require("readline"),A=require("path"),ge=require("os");var Hp=new Set(["New session","Resumed session","Untitled session"]),Fp=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function Up(t){return t.replace(/\s+/g," ").trim()}function Jr(t){return typeof t!="string"?void 0:Up(t)||void 0}function tc(t){let e=Jr(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 ht(t){let e=Jr(t);return!e||Hp.has(e)||tc(e)}function qp(t){for(let e of t.replace(/\r/g,"").split(`
92
- `)){let r=Jr(e);if(r&&!Wp(r)&&!jp(r))return r}}function Wp(t){return Fp.some(e=>t.startsWith(e))}function jp(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function Gp(t){for(let e=0;e<t.length;e+=1){let r=t[e];if(r==="\u3002"||r==="\uFF01"||r==="\uFF1F"||r==="\uFF1B")return e+1;if(r==="."||r==="!"||r==="?"||r===";"){let n=t[e+1];if(!n||/\s/.test(n))return e+1}}return-1}function Os(t,e=80){if(typeof t!="string")return;let r=qp(t);if(!r)return;let n=Gp(r),i=(n>0?r.slice(0,n):r).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||tc(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function je(t,e){for(let r of t){let n=Jr(r);if(!(!n||ht(n)))return n}return Os(e)}var nc=require("child_process"),pt=require("fs/promises"),Ae=require("path"),Bs=require("os"),sc=require("util");var zp=(0,sc.promisify)(nc.execFile),$p=15e3,tr=null;function Xr(){tr=null}function Vp(t){return t.replace(/^['"]|['"]$/g,"")}function Yp(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(Vp)}function Ds(t){let e=Yp(t);for(let r=0;r<e.length;r+=1){let n=e[r],s=(0,Ae.basename)(n);if(s==="claude"||s==="codex")return{agent:s,args:e.slice(r+1)}}return null}function Jp(t,e){let r=Ds(e);if(!r||r.agent!==t)return null;let{args:n}=r;if(t==="claude"){for(let s=0;s<n.length;s+=1){let i=n[s];if((i==="--resume"||i==="--session-id")&&n[s+1]&&!n[s+1].startsWith("-"))return n[s+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(n[0]!=="resume")return null;for(let s=1;s<n.length;s+=1){let i=n[s];if(!i.startsWith("-"))return i}return null}function Kr(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function Kp(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function Xp(t,e){let r=Ds(e);return!r||r.agent!==t?!1:r.args.includes("--continue")||r.args.includes("-c")}function Zp(t){let e=Jp(t.agent,t.command);if(e)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:e,confidence:"high"};let r=[...new Set(t.sessionFiles)].filter(s=>Kp(t.agent,s));if(r.length!==1)return null;let n=gt(t.agent,r[0]);return n?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:n,confidence:"medium",sessionFilePath:r[0]}:null}function Qp(t,e){let r=t,n=e;return(Kr(e.confidence)>Kr(t.confidence)||Kr(e.confidence)===Kr(t.confidence)&&e.pid<t.pid)&&(r=e,n=t),{...r,cwd:r.cwd||n.cwd,title:r.title??n.title,sessionFilePath:r.sessionFilePath??n.sessionFilePath}}function eg(t){let e=new Map;for(let r of t){let n=`${r.agent}:${r.sessionId}`,s=e.get(n);e.set(n,s?Qp(s,r):r)}return[...e.values()]}async function Hs(t,e){try{let{stdout:r}=await zp(t,e,{maxBuffer:8388608});return r}catch{return""}}async function rc(t){if(!t.sessionFilePath)return t;let e=await rr(t.sessionFilePath,t.agent);return e?{...t,cwd:t.cwd||e.cwd,title:t.title??e.title}:null}async function tg(t){return(await Hs("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
93
- `).find(n=>n.startsWith("n"))?.slice(1).trim()??""}async function rg(t){let r=(await Hs("lsof",["-p",String(t),"-Fn"])).split(`
94
- `).filter(n=>n.startsWith("n")).map(n=>n.slice(1).trim()).filter(n=>n.endsWith(".jsonl")?n.includes("/.claude/projects/")||n.includes("/.codex/sessions/"):!1);return[...new Set(r)]}async function ng(){return(await Hs("pgrep",["-fal","(^|/)(claude|codex)( |$)|claude app-server|codex app-server"])).split(`
95
- `).map(e=>e.trim()).filter(Boolean).map(e=>{let r=e.match(/^(\d+)\s+(.*)$/);if(!r)return null;let n=Number(r[1]),s=r[2],i=Ds(s);return!Number.isFinite(n)||!i?null:{pid:n,command:s,agent:i.agent}}).filter(e=>!!e)}async function sg(){let t=await ng();return Promise.all(t.map(async e=>({pid:e.pid,agent:e.agent,command:e.command,cwd:await tg(e.pid),sessionFiles:await rg(e.pid)})))}function ig(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function og(t,e){if(!e)return null;try{if(t==="claude"){let o=(0,Ae.join)((0,Bs.homedir)(),".claude","projects",ig(e)),l=(await(0,pt.readdir)(o).catch(()=>[])).filter(f=>f.endsWith(".jsonl"));if(l.length===0)return null;let c=null;if(await Promise.all(l.map(async f=>{let h=await(0,pt.stat)((0,Ae.join)(o,f)).catch(()=>null);h&&(!c||h.mtimeMs>c.mtimeMs)&&(c={name:f,mtimeMs:h.mtimeMs})})),!c)return null;let u=(0,Ae.join)(o,c.name),d=gt(t,u);return d?{sessionId:d,filePath:u}:null}let r=(0,Ae.join)((0,Bs.homedir)(),".codex","sessions"),n=null;async function s(o){let a=await(0,pt.readdir)(o,{withFileTypes:!0}).catch(()=>[]);for(let l of a){let c=(0,Ae.join)(o,l.name);if(l.isDirectory())await s(c);else if(l.name.endsWith(".jsonl")){let u=await(0,pt.stat)(c).catch(()=>null);if(!u||n&&u.mtimeMs<=n.mtimeMs)continue;let d=await rr(c,t);if(!d||d.cwd!==e)continue;n={path:c,mtimeMs:u.mtimeMs,sessionId:d.sessionId}}}}await s(r);let i=n;return i?{sessionId:i.sessionId,filePath:i.path}:null}catch{return null}}async function ic(){if(tr&&Date.now()<tr.expiresAt)return tr.value;let t=await sg(),e=await Promise.all(t.map(async n=>{let s=Zp(n);if(s)return rc(s);if(Xp(n.agent,n.command))return null;let i=await og(n.agent,n.cwd);return i?rc({agent:n.agent,pid:n.pid,cwd:n.cwd,command:n.command,sessionId:i.sessionId,confidence:"low",sessionFilePath:i.filePath}):null})),r=eg(e.filter(n=>n!==null));return tr={value:r,expiresAt:Date.now()+$p},r}var ac=L.child({module:"inventory"}),mt={daemonActive:3,externalRunning:2,idle:1},oc={high:3,medium:2,low:1};function lc(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function ag(t,e){let r=t.runtime.needsAttention?1:0,n=e.runtime.needsAttention?1:0,s=t.runtime.isResponding?1:0,i=e.runtime.isResponding?1:0;return n-r||i-s||mt[e.runtime.state]-mt[t.runtime.state]||lc(t,e)}function lg(t,e){return mt[e.state]>mt[t.state]?e:mt[e.state]<mt[t.state]?t:oc[e.confidence]>oc[t.confidence]?e:t}function cg(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function ug(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function dg(t,e){return e?t?!(ht(e)&&!ht(t)):!0:!1}function Fs(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function fg(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:Fs(),managed:t.managed,approvalMode:t.approvalMode}}function hg(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",pid:t.pid,command:t.command}}}function pg(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 gg(t,e){for(let r of e){let n=`${r.agent}:${r.sessionId}`,s=t.get(n);if(!s){t.set(n,{...r,sources:[...r.sources],runtime:{...r.runtime}});continue}let i=dg(s.title,r.title)?r.title:s.title,o=r.cwd||s.cwd,a=lg(s.runtime,r.runtime),l=s.sources.slice();for(let f of r.sources)l.includes(f)||l.push(f);let c=r.sources.includes("process"),u=s.sources.includes("process")&&!s.sources.includes("daemon"),d=c?s.lastActivityAt:u?r.lastActivityAt:ug(s.lastActivityAt,r.lastActivityAt);t.set(n,{...s,cwd:o,title:i,createdAt:cg(s.createdAt,r.createdAt),lastActivityAt:d,sources:l,runtime:a,managed:s.managed||r.managed,approvalMode:r.approvalMode??s.approvalMode})}}function mg(...t){let e=new Map;for(let r of t)gg(e,r);return[...e.values()]}function yg(t,e,r,n,s){let i=n?.toLowerCase(),o=t.filter(a=>{if(e&&a.agent!==e||r&&a.cwd!==r)return!1;if(i){let l=(a.title??"").toLowerCase(),c=(a.cwd??"").toLowerCase(),u=l.includes(i)||c.includes(i),d=s?.has(a.sessionId)??!1;if(!u&&!d)return!1}return!0});return n&&ac.info({total:t.length,filtered:o.length,search:n,contentMatchIds:s?.size??0},"filter applied"),o}function Sg(t,e){if(!e)return 0;let r=0,n=t.length;for(;r<n;){let s=r+n>>1,i=t[s];(e.lastActivityAt.localeCompare(i.lastActivityAt)||i.sessionId.localeCompare(e.sessionId))>0?n=s:r=s+1}if(r>0){let s=t[r-1];if(s.lastActivityAt===e.lastActivityAt&&s.sessionId===e.sessionId)return r}return 0}function _g(t,e,r,n,s,i,o){let a=i?1/0:Math.max(1,e||50),l=mg(t.sessionRecords.map(fg),t.scannedSessions,t.runningSessions.map(S=>hg(S,t.scannedAt)),t.activeSessions.map(pg)),c=t.deletedSessionIds?.size?l.filter(S=>!t.deletedSessionIds?.has(S.sessionId)):l,u=yg(c,n,s,i,o),d=u.filter(S=>S.runtime.state!=="idle"||S.managed).sort(ag),f=u.filter(S=>S.runtime.state==="idle"&&!S.managed).sort(lc),h=Sg(f,r),p=f.slice(h,h+a),y=h+p.length<f.length&&p.length>0?{lastActivityAt:p[p.length-1].lastActivityAt,sessionId:p[p.length-1].sessionId}:void 0;return{sessions:r?p:[...d,...p],nextCursor:y}}async function Zr(t){let e=new Date().toISOString(),[r,n,s]=await Promise.all([nr(t.agent,t.cwd),ic(),t.search?cc(t.search,t.agent):Promise.resolve(void 0)]);return t.search&&ac.info({search:t.search,contentMatches:s?.size??0,scanned:r.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results"),_g({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:r,runningSessions:n,scannedAt:e,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,t.search,s)}var Ce=L.child({module:"scanner"});function pc(t){let e=new Map;return{get(r){let n=e.get(r);if(n){if(Date.now()>n.expiresAt){e.delete(r);return}return n.value}},set(r,n){e.set(r,{value:n,expiresAt:Date.now()+t})},clear(){e.clear()}}}var gc=3e4,qs=pc(gc),Ws=pc(gc),Qr=8;function tn(){qs.clear(),Ws.clear()}function js(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function en(t,e,r){if(t.length===0)return[];let n=Math.max(1,Math.min(e,t.length)),s=new Array(t.length),i=0;return await Promise.all(Array.from({length:n},async()=>{for(;;){let o=i;if(i+=1,o>=t.length)return;s[o]=await r(t[o],o)}})),s}function*mc(t,e){let r=0,n=0;for(;r<t.length&&n<e;){let s=t.indexOf(`
96
- `,r);s===-1&&(s=t.length);let i=t.substring(r,s);r=s+1,!(i.length===0||i.trim().length===0)&&(yield i,n+=1)}}var Us=512*1024;async function yc(t,e){if(e<=Us)return(0,B.readFile)(t,"utf-8");let r=await(0,B.open)(t,"r");try{let n=Buffer.alloc(Us),{bytesRead:s}=await r.read(n,0,Us,0);return n.toString("utf-8",0,s)}finally{await r.close()}}function $s(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 Sc(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?$s(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function Vs(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 vg=["<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 wg(t,e){if(t?.isMeta===!0)return!0;let r=e.trim();return r?vg.some(n=>r.startsWith(n)):!1}function Ys(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=Vs(t.message.content);return wg(t,e)?"":e}function _c(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function vc(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:Fs()}}function gt(t,e){let r=(0,A.basename)(e,".jsonl");return t==="claude"?r||null:r.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 bg(t,e){let r=await yc(t,e),n=mc(r,64),s="",i="",o,a,l;for(let c of n){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=je([u.customTitle,u.summary])),!l){let d=Ys(u),f=je([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||gt("claude",t)||(0,A.basename)(t,".jsonl"),cwd:s,title:o??l??je([],a)}:null}async function Ig(t,e){let r=await yc(t,e),n=mc(r,96),s="",i="",o,a,l;for(let c of n){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=je([u.payload?.title,u.title])),!l){let d=Sc(u),f=d&&!_c(d)?je([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||gt("codex",t)||(0,A.basename)(t,".jsonl"),cwd:s,title:o??l??je([],a)}:null}async function rr(t,e){let r=await(0,B.stat)(t).catch(()=>null);if(!r)return null;try{let n=r.size;if(e==="claude"){let i=await bg(t,n);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,createdAt:new Date(r.birthtimeMs).toISOString(),lastActivityAt:new Date(r.mtimeMs).toISOString(),filePath:t}:null}let s=await Ig(t,n);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,createdAt:new Date(r.birthtimeMs).toISOString(),lastActivityAt:new Date(r.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function uc(t){let e=(0,A.join)((0,ge.homedir)(),".claude","projects");try{let r;t?r=[js(t)]:r=(await(0,B.readdir)(e,{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name);let n=[];for(let o of r){let a=(0,A.join)(e,o),l=await(0,B.readdir)(a).catch(()=>[]);for(let c of l)c.endsWith(".jsonl")&&n.push((0,A.join)(a,c))}return(await en(n,Qr,o=>rr(o,"claude"))).filter(o=>o!==null).map(o=>vc(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(r){return Ce.warn({error:String(r)},"failed to list claude sessions"),[]}}async function dc(t){let e=(0,A.join)((0,ge.homedir)(),".codex","sessions");try{let r=await(0,B.readdir)(e).catch(()=>[]),n=[];for(let o of r){let a=(0,A.join)(e,o),l=await(0,B.readdir)(a).catch(()=>[]);for(let c of l){let u=(0,A.join)(a,c),d=await(0,B.readdir)(u).catch(()=>[]);for(let f of d){let h=(0,A.join)(u,f),p=await(0,B.readdir)(h).catch(()=>[]);for(let g of p)g.endsWith(".jsonl")&&n.push((0,A.join)(h,g))}}}return(await en(n,Qr,o=>rr(o,"codex"))).filter(o=>o!==null).filter(o=>!t||o.cwd===t).map(o=>vc(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(r){return Ce.warn({error:String(r)},"failed to list codex sessions"),[]}}async function nr(t,e){let n=`list:${(0,ge.homedir)()}:${t??"all"}:${e??""}`,s=qs.get(n);if(s)return s;let i;if(t==="claude")i=await uc(e);else if(t==="codex")i=await dc(e);else{let[o,a]=await Promise.all([uc(e),dc(e)]);i=[...o,...a].sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}return qs.set(n,i),i}async function cc(t,e){let n=`search:${(0,ge.homedir)()}:${t}:${e??"all"}`,s=Ws.get(n);if(s)return s;let i=new Set,o=t.toLowerCase();async function a(){let c=(0,A.join)((0,ge.homedir)(),".claude","projects");try{let u=await(0,B.readdir)(c,{withFileTypes:!0}),d=[];for(let h of u){if(!h.isDirectory())continue;let p=(0,A.join)(c,h.name),g=await(0,B.readdir)(p).catch(()=>[]);for(let y of g)y.endsWith(".jsonl")&&d.push((0,A.join)(p,y))}let f=await en(d,Qr,h=>fc(h,o,"claude"));for(let h of f)h&&i.add(h)}catch(u){Ce.warn({error:String(u)},"failed to search claude files")}}async function l(){let c=(0,A.join)((0,ge.homedir)(),".codex","sessions");try{let u=[];async function d(h){let p=await(0,B.readdir)(h,{withFileTypes:!0}).catch(()=>[]);for(let g of p){let y=(0,A.join)(h,g.name);g.isDirectory()?await d(y):g.name.endsWith(".jsonl")&&u.push(y)}}await d(c);let f=await en(u,Qr,h=>fc(h,o,"codex"));for(let h of f)h&&i.add(h)}catch(u){Ce.warn({error:String(u)},"failed to search codex files")}}return e==="claude"?await a():e==="codex"?await l():await Promise.all([a(),l()]),Ws.set(n,i),i}async function fc(t,e,r){let n=(0,Gs.createReadStream)(t,{encoding:"utf-8"}),s=(0,zs.createInterface)({input:n,crlfDelay:1/0}),i=r==="claude"?xg:Tg,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||(r==="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(),n.destroy()}return a?o||gt(r,t):null}function xg(t){return t?.type==="user"&&t.message?.role==="user"?Ys(t):t?.type==="assistant"&&t.message?.role==="assistant"?Vs(t.message.content):""}function Tg(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let r=t.payload.role;if(r==="user"||r==="assistant")return $s(t.payload.content)}let e=Sc(t);return e||""}async function hc(t,e){let r=(0,Gs.createReadStream)(t,{encoding:"utf-8"}),n=(0,zs.createInterface)({input:r,crlfDelay:1/0});try{for await(let s of n){if(!s.trim())continue;let i;try{i=JSON.parse(s)}catch{continue}if(e(i))break}}finally{n.close(),r.destroy()}}async function sr(t,e,r){let n=[];if(e==="claude"){let s=(0,A.join)((0,ge.homedir)(),".claude","projects");try{let i=r?[js(r)]:[],o=await(0,B.readdir)(s).catch(()=>[]),a=r?[...i,...o.filter(l=>l!==js(r))]:o;for(let l of a){let c=(0,A.join)(s,l,`${t}.jsonl`);try{if(await hc(c,u=>{if(u.type==="user"&&u.message?.role==="user"){let d=Ys(u);d&&n.push({role:"user",content:d})}else if(u.type==="assistant"&&u.message?.role==="assistant"){let d=Vs(u.message.content);d&&n.push({role:"assistant",content:d})}}),n.length>0)break}catch(u){u.code!=="ENOENT"&&Ce.warn({error:String(u)},"failed to read claude session file")}}}catch(i){Ce.warn({error:String(i)},"failed to read claude session history")}}else if(e==="codex"){let s=(0,A.join)((0,ge.homedir)(),".codex","sessions");try{let i=await wc(s,t);i&&await hc(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=$s(o.payload.content);l&&(a==="user"&&_c(l)||n.push({role:a,content:l}))})}catch(i){Ce.warn({error:String(i)},"failed to read codex session history")}}return n}async function wc(t,e){try{let r=await(0,B.readdir)(t,{withFileTypes:!0});for(let n of r){let s=(0,A.join)(t,n.name);if(n.isDirectory()){let i=await wc(s,e);if(i)return i}else if(n.name.includes(e)&&n.name.endsWith(".jsonl"))return s}}catch(r){Ce.warn({error:String(r)},"failed to walk codex sessions dir")}return null}var yt=require("fs"),xc=require("path");var kg=500,bc=200;function Eg(t){if(!Array.isArray(t))return[];let e=t.filter(r=>typeof r=="string"&&r.length>0);return e.length<=bc?e:e.slice(-bc)}function Ag(t){if(!Array.isArray(t))return[];let e=[];for(let r of t)typeof r!="string"||r.length===0||e.includes(r)||e.push(r);return e}function Ic(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:Eg(t.acceptedClientMessageIds)}}function Cg(t){if(Array.isArray(t))return{records:t.map(Ic),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(Ic):[],deletedSessionIds:Ag(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var rn=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(r=>r.sessionId===e)}isDeleted(e){return this.deletedSessionIds.has(e)}upsert(e){this.deletedSessionIds.delete(e.sessionId);let r=this.records.findIndex(n=>n.sessionId===e.sessionId);r>=0?this.records[r]=e:this.records.unshift(e),this.scheduleSave()}remove(e){this.records=this.records.filter(r=>r.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()},kg)}loadFromDisk(){try{let e=(0,yt.readFileSync)(Hr,"utf-8");return Cg(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,yt.mkdirSync)((0,xc.dirname)(Hr),{recursive:!0}),(0,yt.writeFileSync)(Hr,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var Tc=require("path"),kc=require("os");function nn(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,Tc.join)((0,kc.homedir)(),t.slice(2)):t}var St=require("fs"),Ec=require("path");function Pg(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 Rg(t){try{let e=(0,St.readFileSync)(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r.filter(Pg):[]}catch{return[]}}function ir(t,e){(0,St.mkdirSync)((0,Ec.dirname)(t),{recursive:!0}),(0,St.writeFileSync)(t,JSON.stringify(e,null,2)+`
97
- `,"utf8")}var sn=class{constructor(e=Tl){this.pushSubscriptionsPath=e;this.records=Rg(e)}records;list(){return this.records.map(e=>({...e}))}listTokens(){return this.records.map(e=>e.pushToken)}count(){return this.records.length}register(e,r){let n=new Date().toISOString(),s=this.records.find(o=>o.deviceId===e),i={deviceId:e,pushToken:r,platform:"expo",createdAt:s?.createdAt??n,updatedAt:n,...s?.lastSentAt?{lastSentAt:s.lastSentAt}:{}};this.records=[i,...this.records.filter(o=>o.deviceId!==e&&o.pushToken!==r)],ir(this.pushSubscriptionsPath,this.records)}unregister(e,r){let n=this.records.filter(s=>!(s.deviceId===e&&s.pushToken===r));return n.length===this.records.length?!1:(this.records=n,ir(this.pushSubscriptionsPath,this.records),!0)}unregisterToken(e){let r=this.records.filter(n=>n.pushToken!==e);return r.length===this.records.length?!1:(this.records=r,ir(this.pushSubscriptionsPath,this.records),!0)}markSent(e){if(e.length===0)return;let r=new Set(e),n=new Date().toISOString(),s=!1;for(let i of this.records)r.has(i.pushToken)&&(i.lastSentAt=n,s=!0);s&&ir(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],ir(this.pushSubscriptionsPath,this.records)}};var z=L.child({module:"push"}),Lg="https://exp.host/--/api/v2/push/send",Mg="https://exp.host/--/api/v2/push/getReceipts",Ng=[0,1e3,3e3],or=new sn;function Og(t){return new Promise(e=>{setTimeout(e,t)})}function Ac(t){return t==="DeviceNotRegistered"}function Bg(t,e){if(!Array.isArray(t.data))return{successfulTokens:[],ticketErrors:[]};let r=[],n=[];for(let[s,i]of t.data.entries()){let o=e[s];if(!(!o||!i||typeof i!="object")){if(i.status==="ok"){r.push(o);continue}n.push({token:o,ticket:i})}}return{successfulTokens:r,ticketErrors:n}}function Dg(t,e){let r=new Map;if(!Array.isArray(t.data))return r;for(let[n,s]of t.data.entries()){let i=e[n];!i||!s||s.status!=="ok"||typeof s.id!="string"||s.id.length===0||r.set(s.id,i)}return r}function Hg(t,e){let r=[],n=[],s=t.data;for(let[i,o]of e.entries()){let a=s?.[i];if(!a||typeof a!="object"){r.push(i);continue}a.status==="error"&&n.push({token:o,receipt:a})}return{pendingTicketIds:r,receiptErrors:n}}async function Fg(t,e,r,n){let s=new Map(t);for(let i of Ng){if(s.size===0)return;i>0&&await r(i);let o;try{o=await e(Mg,{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}=Hg(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"),Ac(f)){let h=n.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 Ug(t){let e=t?.pushStore??or,r=t?.fetchImpl??globalThis.fetch,n=t?.sleepImpl??Og;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}));try{let u=await r(Lg,{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}=Bg(d,l),p=Dg(d,l);for(let{token:g,ticket:y}of h){let S=y.details?.error;if(z.error({token:g,message:y.message,details:y.details,ticketStatus:y.status},"push ticket rejected"),Ac(S)){let U=e.unregisterToken(g);z.info({token:g,errorCode:S,removed:U},"push token removed after ticket rejection")}}f.length>0&&(z.debug({count:f.length},"push sent"),e.markSent(f)),p.size>0&&await Fg(p,r,n,e)}catch(u){z.error({error:String(u)},"push send error")}}}function Js(t,e){or.register(t,e),z.info({deviceId:t,token:e,total:or.count()},"push token registered")}function Ks(t,e){let r=or.unregister(t,e);z.info({deviceId:t,token:e,total:or.count(),removed:r},"push token unregistered")}var Cc=Ug();var v=L.child({module:"manager"}),qg="Done.",Pc=180,an=200;function on(...t){let e=[];for(let r of t)if(r?.length)for(let n of r)!n||e.includes(n)||(e.push(n),e.length>an&&e.splice(0,e.length-an));return e}function me(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:on(t.acceptedClientMessageIds),title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,managed:t.managed}}function Rc(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&Vr(e)}function Wg(t){return t.startsWith(Cs)}function Lc(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 ln=class{constructor(e=Cc){this.pushSender=e;this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new rn;idleSweepInterval=null;startIdleSweep(){_.idleTimeoutMs<=0&&_.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(),r=_.idleTimeoutMs,n=_.turnStallTimeoutMs;if(r<=0&&n<=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&&(v.info({sessionId:o.sessionId,inactiveMs:l},"removing inactive session from memory"),b.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(n<=0||o.pendingApproval||a<n)continue;v.warn({sessionId:o.sessionId,agent:o.agent,inactiveMs:a,turnStallTimeoutMs:n},"stopping stalled driver"),b.increment("driver.stall_timeout",{agent:o.agent}),w.emit("driver.stall_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),o.isResponding=!1,o.currentReplyText="",this.broadcast(o.sessionId,{type:"error",sessionId:o.sessionId,message:`Agent stopped responding for over ${Math.ceil(n/1e3)}s. Send a new message to continue.`}),o.driver.stop(),o.active=!1,o.driver=null,this.updateGauges(),this.touchSession(o.sessionId);continue}r<=0||a<r||(v.info({sessionId:o.sessionId,agent:o.agent,idleMs:a,timeoutMs:r},"stopping idle driver"),b.increment("driver.idle_timeout",{agent:o.agent}),w.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))}}bindDriverLifecycle(e,r,n,s){e.driver?.onMessage(i=>{v.debug({agent:r,context:n,msgType:i.type,sessionId:e.sessionId},"driver message received"),i.type!=="response"&&i.sessionId&&i.sessionId!==e.sessionId&&!this.sessions.has(i.sessionId)&&this.remapSessionId(e,i.sessionId,s),(i.type==="session.done"||i.type==="session.interrupted")&&(e.isResponding=!1,(i.type==="session.interrupted"||!Rc(e))&&(e.pendingApproval=void 0)),i.type==="approval.request"&&(e.isResponding=!1,e.pendingApproval={requestId:i.requestId,toolName:i.toolName,input:i.input,description:i.description}),r==="claude"&&i.type==="approval.request"&&Vr(i.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[i.requestId]={message:e.lastUserMessage,toolName:i.toolName}:v.warn({sessionId:e.sessionId,requestId:i.requestId},"missing lastUserMessage for synthetic approval retry")),this.touchSession(e.sessionId,i.type!=="text.delta"),this.broadcast(e.sessionId,i),(i.type==="session.done"||i.type==="session.interrupted")&&e.bufferedPrompts.length>0&&this.flushBufferedPrompt(e)}),e.driver?.onExit?.(i=>{v.info({agent:r,context:n,exitCode:i,sessionId:e.sessionId},"driver exited"),w.emit("driver.exit",{sessionId:e.sessionId,agent:r,exitCode:i}),b.increment("driver.exit",{agent:r,abnormal:i&&i!==0?"true":"false"});let o=i===0&&Rc(e);this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",o||(e.pendingApproval=void 0),this.updateGauges(),this.touchSession(e.sessionId)})}remapSessionId(e,r,n){if(!r||r===e.sessionId)return;let s=this.sessions.get(r);if(s&&s!==e){v.warn({oldSessionId:e.sessionId,newSessionId:r},"skipping session ID remap because target already exists");return}let i=e.sessionId;v.info({oldSessionId:i,newSessionId:r},"session ID updated"),this.store.remove(i),this.sessions.delete(i),e.sessionId=r,this.sessions.set(r,e),this.store.upsert(me(e)),n&&this.reply(n,`id_update_${Date.now()}`,!0,{sessionId:r,oldSessionId:i})}flushBufferedPrompt(e,r=!1){if(!e.driver||!e.active||e.startupInProgress||e.pendingApproval||!r&&e.isResponding)return!1;let n=e.bufferedPrompts.shift();return n?(e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=n,this.touchSession(e.sessionId),e.driver.sendPrompt(n),!0):!1}startPendingCodexSession(e,r){if(e.agent!=="codex"||!e.driver)return;let n=e.driver,s=e.sessionId,i=e.startupToken,o=b.startTimer("driver.spawn");(async()=>{try{let a=await n.start(e.cwd,void 0,e.approvalMode),l=o();if(this.sessions.get(s)!==e||e.startupToken!==i||e.driver!==n){v.info({pendingSessionId:s,actualSessionId:a},"discarding stale codex startup result");return}e.startupInProgress=!1,v.info({pendingSessionId:s,sessionId:a,spawnMs:l},"codex session ready"),a&&a!==s&&this.remapSessionId(e,a,r),this.flushBufferedPrompt(e,!0)}catch(a){if(o(),this.sessions.get(s)!==e||e.startupToken!==i){v.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),v.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,r,n){if(e!=="claude"||!(r instanceof er))return;let s=n??(0,Xs.randomUUID)().replace(/-/g,"");return r.configureHookBridge(_.port,s),s}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,r=Qt){for(let n of e.pendingClaudeHookApprovals.values())n.resolve(r);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&Wg(e.pendingApproval.requestId)&&(e.pendingApproval=void 0)}resolveClaudeHookSession(e){if(!e)return;let r=e.trim();if(r)return this.claudeHookSessions.get(r)}handleClaudeSessionStartHook(e,r){let n=this.resolveClaudeHookSession(e);return n?(this.touchSession(n.sessionId),!0):(v.warn({secretPresent:!!e},"received Claude session-start hook for unknown session"),!1)}async handleClaudePermissionHook(e,r){let n=this.resolveClaudeHookSession(e);if(!n||n.agent!=="claude"||!n.active)return v.warn({secretPresent:!!e},"received Claude permission hook for unknown or inactive session"),Qt;if(n.approvalMode==="autoApprove")return Lc(!0);let i=(typeof r.tool_name=="string"?r.tool_name:typeof r.toolName=="string"?r.toolName:"").trim();if(!i)return Qt;let o=r.tool_input??r.toolInput,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},l=typeof r.tool_use_id=="string"?r.tool_use_id:typeof r.toolUseId=="string"?r.toolUseId:"",c=`${Cs}${l.trim()||(0,Xs.randomUUID)()}`,u=n.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${i}.`,f,h=new Promise(p=>{f=p});return n.pendingClaudeHookApprovals.set(c,{requestId:c,promise:h,resolve:p=>{n.pendingClaudeHookApprovals.delete(c),f(p)}}),n.pendingApproval={requestId:c,toolName:i,input:a,description:d},w.emit("approval.request",{agent:"claude",sessionId:n.sessionId,toolName:i}),this.touchSession(n.sessionId),this.broadcast(n.sessionId,{type:"approval.request",sessionId:n.sessionId,requestId:c,toolName:i,input:a,description:d}),h}async resolveReconnectSession(e,r,n){if(this.isDeletedSession(e))return;let s=new Date().toISOString(),i=n?.agent,o=n?.cwd??"",a=n?.approvalMode,l=n?.title??"",c=n?.createdAt??s,u=n?.lastActivityAt??s,d=on(n?.acceptedClientMessageIds),f=n?"memory":"client",h=this.store.find(e);if(h)i=h.agent,o=h.cwd||o,a=h.approvalMode??a,l=h.title||l,c=h.createdAt||c,u=h.lastActivityAt||u,d=on(h.acceptedClientMessageIds,d),f="record";else if(!n){let g=(await nr(r??i)).find(y=>y.sessionId===e);g&&(i=g.agent,o=g.cwd||o,l=g.title??l,c=g.createdAt,u=g.lastActivityAt,f="scanner")}if(!i&&r&&(i=r,f=n?"memory":"client"),!!i)return{agent:i,cwd:o,approvalMode:a,title:l,createdAt:c,lastActivityAt:u,acceptedClientMessageIds:d,source:f,managed:n?.managed??h?.managed}}resendPendingApproval(e,r){if(!e.pendingApproval||r.readyState!==1)return;let{requestId:n,toolName:s,input:i,description:o}=e.pendingApproval;v.info({sessionId:e.sessionId,requestId:n,toolName:s},"resending pending approval to reconnected client");let a={type:"approval.request",sessionId:e.sessionId,requestId:n,toolName:s,input:i,description:o};r.send(JSON.stringify(a))}buildPushBody(e){let r=e.replace(/\s+/g," ").trim();return r?r.length<=Pc?r:`${r.slice(0,Math.max(1,Pc-3)).trimEnd()}...`:qg}currentPartialReplyText(e){return e?.isResponding&&e.currentReplyText.trim()?e.currentReplyText:void 0}touchSession(e,r=!0){let n=new Date().toISOString(),s=this.sessions.get(e);if(s){s.lastActivityAt=n,s.lastActivityTs=Date.now(),r&&this.store.upsert(me(s));return}let i=this.store.find(e);i&&this.store.upsert({...i,lastActivityAt:n})}updateGauges(){let e=0;for(let r of this.sessions.values())r.active&&e++;b.gauge("session.active",e)}activeSessionSnapshots(){let e=[];for(let r of this.sessions.values())r.sessionId.startsWith("pending_")||r.active&&e.push({sessionId:r.sessionId,agent:r.agent,cwd:r.cwd,approvalMode:r.approvalMode,title:r.title,createdAt:r.createdAt,lastActivityAt:r.lastActivityAt,...r.pendingApproval?{needsAttention:!0}:{},...r.isResponding?{isResponding:!0}:{},managed:r.managed});return e}getDeletedSessionIds(){return new Set(this.store.getDeletedSessionIds())}isDeletedSession(e){return this.store.isDeleted(e)}async listRecentSessionsForContinue(e,r){return nr(e,r)}async handle(e,r){switch(v.debug({action:r.action},"handling client message"),r.action){case"session.create":await this.createSession(e,r.id,r.agent,r.cwd,r.approvalMode,r.continueSession);break;case"session.resume":await this.resumeSession(e,r.id,r.sessionId,r.agent);break;case"session.send":await this.sendMessage(e,r.id,r.sessionId,r.message,r.agent,r.clientMessageId);break;case"session.approve":await this.approve(e,r.id,r.sessionId,r.requestId,r.approved);break;case"session.setApprovalMode":await this.setApprovalMode(e,r.id,r.sessionId,r.approvalMode);break;case"session.interrupt":this.interrupt(e,r.id,r.sessionId);break;case"session.stop":this.stopSession(e,r.id,r.sessionId);break;case"session.delete":this.deleteSession(e,r.id,r.sessionId);break;case"session.history":await this.sendHistory(e,r.id,r.sessionId,r.agent);break;case"reconnect.snapshot":await this.sendReconnectSnapshot(e,r.id,r.agent,r.cwd,r.search,r.activeSessionId,r.activeAgent);break;case"sessions.list":await this.listSessions(e,r.id,r.agent,r.cwd,r.search,r.limit,r.cursor);break}}removeClient(e){for(let r of this.sessions.values())r.clients.delete(e)}shutdown(){this.stopIdleSweep();for(let e of this.sessions.values()){try{this.resolvePendingClaudeHookApprovals(e),e.driver?.stop()}catch(r){v.error({sessionId:e.sessionId,agent:e.agent,error:String(r)},"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 r of this.sessions.values())r.active&&e++;return e}prewarmCaches(){Zr({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()}).catch(()=>{})}getDriverCounts(){let e={};for(let r of this.sessions.values())r.active&&(e[r.agent]=(e[r.agent]??0)+1);return e}async createSession(e,r,n,s,i,o){s=nn(s),v.info({agent:n,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,Mc.stat)(s)).isDirectory()){this.reply(e,r,!1,void 0,`Path is not a directory: ${s}`);return}}catch{this.reply(e,r,!1,void 0,`Directory does not exist: ${s}`);return}if(o)try{let l=(await this.listRecentSessionsForContinue(n,s)).find(c=>!this.isDeletedSession(c.sessionId));if(l)return v.info({sessionId:l.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,r,l.sessionId,n,s,i);v.info("continue mode: no previous sessions found, creating new")}catch(a){v.warn({error:String(a)},"continue mode: error finding sessions, creating new")}try{let a=this.createDriver(n),l=this.configureDriverBeforeStart(n,a);if(n==="codex"){let h=`pending_${Date.now()}`;v.info({sessionId:h,agent:n,cwd:s},"session created (pending codex startup)"),b.increment("session.create",{agent:n}),w.emit("session.create",{sessionId:h,agent:n,cwd:s,approvalMode:i});let p={sessionId:h,agent:n,cwd:s,approvalMode:i,driver:a,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,bufferedPrompts:[],startupToken:1,managed:!0,claudeHookSecret:l,pendingClaudeHookApprovals:new Map};this.sessions.set(h,p),this.registerClaudeHookSession(p),this.store.upsert(me(p)),this.updateGauges(),tn(),Xr(),this.bindDriverLifecycle(p,n,"",e),this.reply(e,r,!0,{sessionId:h}),this.startPendingCodexSession(p,e);return}let c=b.startTimer("driver.spawn"),u=await a.start(s,void 0,i),d=c();v.info({sessionId:u,agent:n,spawnMs:d},"session created"),b.increment("session.create",{agent:n}),w.emit("session.create",{sessionId:u,agent:n,cwd:s,approvalMode:i});let f={sessionId:u,agent:n,cwd:s,approvalMode:i,driver:a,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:!0,claudeHookSecret:l,pendingClaudeHookApprovals:new Map};this.sessions.set(u,f),this.registerClaudeHookSession(f),this.store.upsert(me(f)),this.updateGauges(),tn(),Xr(),this.bindDriverLifecycle(f,n,"",e),this.reply(e,r,!0,{sessionId:u})}catch(a){v.error({agent:n,cwd:s,error:String(a)},"createSession error"),this.reply(e,r,!1,void 0,String(a))}}async resumeSession(e,r,n,s,i,o){if(this.isDeletedSession(n)){this.reply(e,r,!1,void 0,"Session not found");return}let a=this.sessions.get(n);if(a&&a.active){a.clients.add(e),this.touchSession(a.sessionId);let f=await sr(n,s,a.cwd),h=this.currentPartialReplyText(a);if(f.length>0||h||a.approvalMode){let p={type:"session.history",sessionId:n,messages:f,isResponding:a.isResponding||void 0,partialReplyText:h,approvalMode:a.approvalMode};e.send(JSON.stringify(p))}this.resendPendingApproval(a,e),this.reply(e,r,!0,{sessionId:n});return}let l=this.store.find(n),c=i||l?.cwd||"",u=o??l?.approvalMode,d=l?.title??"Resumed session";try{let f=b.startTimer("driver.spawn"),h=this.createDriver(s),p=this.configureDriverBeforeStart(s,h),g=await h.start(c,n,u),y=f();v.info({sessionId:g,agent:s,spawnMs:y},"session resumed"),b.increment("session.resume",{agent:s}),w.emit("session.resume",{sessionId:g,agent:s,cwd:c});let S={sessionId:g,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??[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:l?.managed,claudeHookSecret:p,pendingClaudeHookApprovals:new Map};this.sessions.set(g,S),this.registerClaudeHookSession(S),this.store.upsert(me(S)),this.updateGauges(),this.bindDriverLifecycle(S,s," (resumed)",e);let U=await sr(n,s,c);if(U.length>0){v.info({sessionId:n,historyCount:U.length},"sending history messages");let se={type:"session.history",sessionId:g,messages:U,approvalMode:u};e.send(JSON.stringify(se))}this.reply(e,r,!0,{sessionId:g})}catch(f){this.reply(e,r,!1,void 0,String(f))}}hasAcceptedClientMessage(e,r){return e.acceptedClientMessageIds.includes(r)}rememberAcceptedClientMessage(e,r){this.hasAcceptedClientMessage(e,r)||(e.acceptedClientMessageIds.push(r),e.acceptedClientMessageIds.length>an&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-an))}async sendMessage(e,r,n,s,i,o){if(this.isDeletedSession(n)){this.reply(e,r,!1,void 0,"Session not found");return}let a=this.sessions.get(n);if(!a||!a.driver){let l=await this.resolveReconnectSession(n,i,a);if(!l){v.warn({sessionId:n},"session not found in records or scanner"),this.reply(e,r,!1,void 0,"Session not found");return}v.info({sessionId:n,agent:l.agent,source:l.source},"auto-reconnecting session"),b.increment("session.reconnect",{agent:l.agent,source:l.source}),w.emit("session.reconnect",{sessionId:n,agent:l.agent,source:l.source});try{let c=this.createDriver(l.agent),u=this.configureDriverBeforeStart(l.agent,c,a?.claudeHookSecret);await c.start(l.cwd,n,l.approvalMode),a?(a.approvalMode=l.approvalMode,a.driver=c,a.active=!0,a.clients.add(e),a.lastActivityAt=l.lastActivityAt,a.lastActivityTs=Date.now(),a.isResponding=!1,a.currentReplyText="",a.acceptedClientMessageIds=on(a.acceptedClientMessageIds,l.acceptedClientMessageIds),a.syntheticApprovalRetries=a.syntheticApprovalRetries??{},a.startupInProgress=!1,a.bufferedPrompts=a.bufferedPrompts??[],a.startupToken=a.startupToken??0,a.claudeHookSecret=u??a.claudeHookSecret,a.pendingClaudeHookApprovals=a.pendingClaudeHookApprovals??new Map):(a={sessionId:n,agent:l.agent,cwd:l.cwd,approvalMode:l.approvalMode,driver:c,clients:new Set([e]),title:l.title,createdAt:l.createdAt,lastActivityAt:l.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:l.acceptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:l.managed,claudeHookSecret:u,pendingClaudeHookApprovals:new Map},this.sessions.set(n,a)),this.registerClaudeHookSession(a),this.bindDriverLifecycle(a,l.agent," (reconnected)"),this.store.upsert(me(a)),this.updateGauges()}catch(c){this.reply(e,r,!1,void 0,`Failed to reconnect: ${c}`);return}}if(a.clients.add(e),o&&this.hasAcceptedClientMessage(a,o)){this.reply(e,r,!0,{sessionId:n,clientMessageId:o,duplicate:!0});return}if(v.info({sessionId:n,clients:a.clients.size,hasDriver:!!a.driver,active:a.active},"sending message"),w.emit("session.send",{sessionId:n,agent:a.agent,messagePreview:s.slice(0,100)}),ht(a.title)){let l=Os(s,50);l&&l!==a.title&&(a.title=l),this.store.upsert(me(a))}if(o&&this.rememberAcceptedClientMessage(a,o),this.touchSession(a.sessionId),a.isResponding=!0,a.currentReplyText="",a.lastUserMessage=s,a.startupInProgress){a.bufferedPrompts.push(s),this.reply(e,r,!0,o?{sessionId:n,clientMessageId:o}:void 0);return}a.driver.sendPrompt(s),this.reply(e,r,!0,o?{sessionId:n,clientMessageId:o}:void 0)}async sendReconnectSnapshot(e,r,n,s,i,o,a){try{let l=this.getDeletedSessionIds(),c;try{c=await Zr({agent:n,cwd:s,search:i,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:l})}catch(d){v.warn({error:String(d)},"failed to build reconnect snapshot session list"),c={sessions:[],nextCursor:void 0}}let u;if(o&&!l.has(o)){let d=a??c.sessions.find(p=>p.sessionId===o)?.agent,f=this.sessions.get(o),h=await this.resolveReconnectSession(o,d,f);if(h){let p=await sr(o,h.agent,f?.cwd??h.cwd);u={sessionId:o,agent:h.agent,messages:p,isResponding:f?.isResponding||void 0,partialReplyText:this.currentPartialReplyText(f),approvalMode:f?.approvalMode??h.approvalMode,...f?.pendingApproval?{pendingApproval:f.pendingApproval}:{}}}}b.increment("reconnect.snapshot",{activeSession:u?"true":"false"}),this.reply(e,r,!0,{snapshot:{sessions:c.sessions,nextCursor:c.nextCursor,...u?{activeSession:u}:{}}})}catch(l){this.reply(e,r,!1,void 0,`Failed to build reconnect snapshot: ${String(l)}`)}}async approve(e,r,n,s,i){let o=this.sessions.get(n),a=o?.pendingClaudeHookApprovals.get(s);if(o&&a){o.pendingApproval=void 0,w.emit("approval.response",{sessionId:n,requestId:s,approved:i}),this.touchSession(o.sessionId),a.resolve(Lc(i)),o.isResponding=!0,this.reply(e,r,!0);return}o&&(o.pendingApproval=void 0);let l=o?.syntheticApprovalRetries[s];if(o&&l&&Vr(s)){delete o.syntheticApprovalRetries[s],w.emit("approval.response",{sessionId:n,requestId:s,approved:i}),this.touchSession(o.sessionId),this.reply(e,r,!0),i&&await this.retrySyntheticClaudeApproval(o,l);return}if(!o?.driver){this.reply(e,r,!1,void 0,"Session not found or inactive");return}if(w.emit("approval.response",{sessionId:n,requestId:s,approved:i}),this.touchSession(o.sessionId),!o.driver.respondApproval(s,i)){this.reply(e,r,!1,void 0,"Agent process is not running. Send a new message to continue.");return}o.isResponding=!0,this.reply(e,r,!0)}async retrySyntheticClaudeApproval(e,r){if(e.agent==="claude")try{e.driver&&e.driver.stop();let n=["Write","Edit","NotebookEdit"].includes(r.toolName)?"acceptEdits":"autoApprove",s=this.createDriver(e.agent),i=this.configureDriverBeforeStart(e.agent,s,e.claudeHookSecret);await s.start(e.cwd,e.sessionId,n),e.driver=s,e.active=!0,e.isResponding=!0,e.currentReplyText="",e.lastUserMessage=r.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(me(e)),this.updateGauges(),this.touchSession(e.sessionId),v.info({sessionId:e.sessionId,toolName:r.toolName,retryApprovalMode:n},"retrying Claude turn after synthetic approval"),s.sendPrompt(r.message)}catch(n){e.driver=null,e.active=!1,e.isResponding=!1,e.startupInProgress=!1,e.bufferedPrompts=[],e.startupToken+=1,this.updateGauges(),this.touchSession(e.sessionId),v.error({sessionId:e.sessionId,error:String(n)},"failed to retry Claude turn after approval"),this.broadcast(e.sessionId,{type:"error",sessionId:e.sessionId,message:`Failed to continue after approval: ${String(n)}`})}}async setApprovalMode(e,r,n,s){let i=this.sessions.get(n);if(!i){let a=this.store.find(n);a?(a.approvalMode=s,this.store.upsert(a),v.info({sessionId:n,agent:a.agent,newMode:s},"approval mode changed (inactive session)")):v.info({sessionId:n,newMode:s},"approval mode changed (untracked session)"),this.reply(e,r,!0,{approvalMode:s});return}let o=i.approvalMode;if(i.approvalMode=s,this.store.upsert(me(i)),v.info({sessionId:n,agent:i.agent,oldMode:o,newMode:s},"approval mode changed"),i.driver&&(i.driver.setApprovalMode(s),i.agent==="codex"&&i.active&&o!==s))try{i.driver.stop();let a=this.createDriver("codex");await a.start(i.cwd,i.sessionId,s),i.driver=a,this.bindDriverLifecycle(i,"codex"," (mode change)"),v.info({sessionId:n},"codex driver restarted with new approval mode")}catch(a){v.error({sessionId:n,error:String(a)},"failed to restart codex after approval mode change"),i.driver=null,i.active=!1,this.updateGauges()}this.reply(e,r,!0,{approvalMode:s})}interrupt(e,r,n){let s=this.sessions.get(n);if(!s?.driver){this.reply(e,r,!1,void 0,"Session not found or inactive");return}w.emit("session.interrupt",{sessionId:n,agent:s.agent}),s.driver.interrupt(),this.reply(e,r,!0)}stopSession(e,r,n){let s=this.sessions.get(n);if(!s){this.reply(e,r,!1,void 0,"Session not found");return}v.info({sessionId:n,agent:s.agent},"stopping session"),w.emit("session.stop",{sessionId:n,agent:s.agent}),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.active=!1,s.driver=null,s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,this.updateGauges(),this.touchSession(s.sessionId),this.reply(e,r,!0)}deleteSession(e,r,n){let s=this.sessions.get(n);s&&(v.info({sessionId:n,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(n)),w.emit("session.delete",{sessionId:n}),this.store.remove(n),this.updateGauges(),tn(),Xr(),this.reply(e,r,!0)}async sendHistory(e,r,n,s){let i=this.sessions.get(n);if(!i&&this.isDeletedSession(n)){this.reply(e,r,!1,void 0,"Session not found");return}i&&i.clients.add(e);let o=i?.cwd??this.store.find(n)?.cwd??"",a=await sr(n,s,o);v.info({sessionId:n,historyCount:a.length,isResponding:i?.isResponding,approvalMode:i?.approvalMode},"sending history");let l={type:"session.history",sessionId:n,messages:a,isResponding:i?.isResponding||void 0,partialReplyText:this.currentPartialReplyText(i),approvalMode:i?.approvalMode};e.send(JSON.stringify(l)),i&&this.resendPendingApproval(i,e),this.reply(e,r,!0)}async listSessions(e,r,n,s,i,o=50,a){try{let l=await Zr({agent:n,cwd:s,search:i,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()});this.reply(e,r,!0,l)}catch(l){this.reply(e,r,!1,void 0,String(l))}}createDriver(e){switch(e){case"claude":return new er;case"codex":return new Yr;default:throw new Error(`Unknown agent: ${e}`)}}broadcast(e,r){let n=this.sessions.get(e);if(!n){v.warn({sessionId:e,msgType:r.type},"broadcast target session not found");return}let s=JSON.stringify(r),i=n.clients.size,o=0,a=0;for(let l of n.clients)l.readyState===1?(l.send(s),o++):a++;if(a>0&&b.increment("broadcast.fail"),r.type!=="text.delta"&&v.debug({sessionId:e,msgType:r.type,sent:o,total:i},"broadcast"),r.type==="text.delta"){n.currentReplyText+=r.content;return}if(r.type==="session.done"){let l=n.title||e,c=this.buildPushBody(n.currentReplyText);n.currentReplyText="",this.pushSender(l,c,{sessionId:e,agent:n.agent});return}r.type==="session.interrupted"&&(n.currentReplyText="")}reply(e,r,n,s,i){if(e.readyState!==1)return;let o={type:"response",id:r,ok:n,data:s,error:i};e.send(JSON.stringify(o))}};function Zs(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 Nc=require("child_process");function jg(t,e){return(0,Nc.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function Gg(t){let e=t.split(`
98
- `).map(r=>Number(r.trim())).filter(r=>Number.isFinite(r)&&r>0);return[...new Set(e)]}function Oc(t,e=jg){let r;try{r=Gg(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return r.map(n=>{try{let s=e("ps",["-p",String(n),"-o","command="]);return s?{pid:n,command:s}:{pid:n}}catch{return{pid:n}}})}var _t=require("fs"),Qs=require("os"),Dc=require("crypto"),Hc=require("path");function Fc(t){return(0,Dc.randomBytes)(t).toString("base64url")}function zg(){return`d_${Fc(12)}`}function $g(){return(0,Qs.hostname)()}function Vg(){let t=(0,Qs.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function Yg(t){return{daemonId:zg(),daemonSecret:Fc(32),displayName:$g(),canonicalHost:Vg(),port:t,createdAt:new Date().toISOString()}}function Bc(t,e){(0,_t.mkdirSync)((0,Hc.dirname)(e),{recursive:!0}),(0,_t.writeFileSync)(e,JSON.stringify(t,null,2)+`
99
- `,"utf8")}function Uc(t,e=Il){try{let n=(0,_t.readFileSync)(e,"utf8"),s=JSON.parse(n);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,Bc(i,e)),i}}catch{}let r=Yg(t);return Bc(r,e),r}var vt=require("crypto"),wt=require("fs"),Wc=require("path");function ei(t){return(0,vt.randomBytes)(t).toString("base64url")}function ti(t){return(0,vt.createHash)("sha256").update(t).digest("hex")}function qc(t,e){let r=Buffer.from(t),n=Buffer.from(e);return r.length!==n.length?!1:(0,vt.timingSafeEqual)(r,n)}function Jg(t){try{let e=(0,wt.readFileSync)(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r.filter(n=>n&&typeof n.deviceId=="string"&&typeof n.deviceName=="string"&&typeof n.tokenHash=="string"&&typeof n.createdAt=="string"&&typeof n.lastSeenAt=="string"&&(typeof n.revokedAt=="string"||n.revokedAt===null)):[]}catch{return[]}}function ar(t,e){(0,wt.mkdirSync)((0,Wc.dirname)(t),{recursive:!0}),(0,wt.writeFileSync)(t,JSON.stringify(e,null,2)+`
100
- `,"utf8")}var cn=class{constructor(e=xl){this.pairingsPath=e;this.records=Jg(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4){let r=`pair_${ei(8)}`,n=ei(24),s=new Date(Date.now()+e).toISOString(),i={pairingId:r,pairNonce:n,expiresAt:s};return this.windows.set(n,i),i}consumeWindow(e){let r=this.windows.get(e);return!r||(this.windows.delete(e),new Date(r.expiresAt).getTime()<Date.now())?null:r}issuePairToken(e,r){let n=new Date().toISOString(),s=ei(32),i={deviceId:e,deviceName:r,tokenHash:ti(s),createdAt:n,lastSeenAt:n,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),ar(this.pairingsPath,this.records),s}validatePairToken(e,r,n=!0){let s=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!s)return!1;let i=ti(r);return qc(s.tokenHash,i)?(n&&(s.lastSeenAt=new Date().toISOString(),ar(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,r=!0){let n=ti(e),s=this.records.find(i=>!i.revokedAt&&qc(i.tokenHash,n));return s?(r&&(s.lastSeenAt=new Date().toISOString(),ar(this.pairingsPath,this.records)),s):null}revoke(e){let r=this.records.find(n=>n.deviceId===e&&!n.revokedAt);return r?(r.revokedAt=new Date().toISOString(),ar(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),ar(this.pairingsPath,this.records)}};function bt(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function Kg(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function jc(t,e){return Kg(t)??e}function ri(t,e){return!!(t&&e&&t===e)}function Gc(t,e,r,n=!0){return t?ri(t,e)?!0:!!r(t,n):!1}var $c=require("child_process");function ni(t){let e=t.split(".");return e.length!==4?!1:e.every(r=>/^\d+$/.test(r)&&Number(r)>=0&&Number(r)<=255)}function Vc(t){if(!ni(t))return!1;let[e,r]=t.split(".").map(Number);return e===100&&r>=64&&r<=127}function Xg(t){if(!ni(t))return!1;let[e,r]=t.split(".").map(Number);return e===169&&r===254}function Zg(t){if(!ni(t))return!1;let[e,r]=t.split(".").map(Number);return e===198&&(r===18||r===19)}function si(t){return!!t&&!Xg(t)&&!Zg(t)}function It(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Yc(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function Qg(t){let e=[],r=[];for(let n of Object.values(t))if(n)for(let s of n)s.internal||s.family!=="IPv4"||si(s.address)&&(Vc(s.address)?e.push(s.address):r.push(s.address));return[...e,...r]}function zc(t){let e=JSON.parse(t),r=It(e.Self?.DNSName),n=(e.Self?.TailscaleIPs??[]).map(o=>It(o)).filter(o=>!!o).filter(o=>Vc(o)&&si(o)),s=n[0]??r,i=[...r&&r!==s?[r]:[],...n.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function Jc(t=$c.execFileSync){let e=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(Boolean);for(let r of e)try{let n=t("tailscale",["--socket",r,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return zc(n)}catch{}try{let r=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return zc(r)}catch{return{fallbackHosts:[]}}}function Kc(t){let e=It(t.canonicalHost),r=It(t.configuredCanonicalHost)||It(t.tailscaleCanonicalHost)||e||"localhost",n=[...e&&e!==r?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...Qg(t.interfaces)].map(s=>It(s)).filter(s=>!!s).filter(s=>si(s)).filter((s,i,o)=>s!==r&&o.indexOf(s)===i);return{canonicalHost:r,fallbackHosts:n}}function Xc(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 j=L.child({module:"daemon"}),lr=L.child({module:"ws"}),ce=new ln,F=Uc(_.port),Re=new cn,un=new Set,Pe=new WeakMap,Zc=!1,ru=Date.now(),xt=null;function Tt(){let t=Jc();return Kc({canonicalHost:F.canonicalHost,configuredCanonicalHost:_.canonicalHost,configuredFallbackHosts:Yc(_.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,eu.networkInterfaces)()})}async function ii(t){let e=[];for await(let n of t)e.push(Buffer.isBuffer(n)?n:Buffer.from(n));let r=Buffer.concat(e).toString("utf8");return r?JSON.parse(r):{}}function D(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r,null,2))}function nu(){let t=Re.openWindow(),e=Tt(),r=e.canonicalHost,n=F.port,s=e.fallbackHosts.length>0?e.fallbackHosts:void 0;if(_.relayUrl)try{let i=new URL(_.relayUrl);r=i.hostname,n=i.port?Number(i.port):i.protocol==="https:"?443:80,s=[e.canonicalHost,...s??[]].filter(Boolean)}catch{j.warn({relayUrl:_.relayUrl},"invalid VIBELET_RELAY_URL, ignoring")}return{type:"vibelet-pair",daemonId:F.daemonId,displayName:F.displayName,canonicalHost:r,fallbackHosts:s,port:n,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function em(t){let e=await(0,Ge.readdir)(t),r=[];for(let n of e){if(n.startsWith("."))continue;let s=await(0,Ge.stat)((0,dn.join)(t,n)).catch(()=>null);s&&r.push({name:n,isDirectory:s.isDirectory()})}return r.sort((n,s)=>n.isDirectory!==s.isDirectory?n.isDirectory?-1:1:n.name.localeCompare(s.name)),{entries:r}}var cr=(0,Qc.createServer)(async(t,e)=>{let r=new URL(t.url??"/",`http://localhost:${_.port}`);if(r.pathname==="/health"){let s=Tt(),i={status:"ok",version:ft,daemonId:F.daemonId,displayName:F.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-ru)/1e3),activeSessions:ce.getActiveSessionCount(),pairedDevices:Re.pairedCount(),wsClients:ne.clients.size,drivers:ce.getDriverCounts(),metrics:b.snapshot()};_.relayUrl&&(i.relayUrl=_.relayUrl),D(e,200,i);return}if(t.method==="POST"&&r.pathname==="/pair/open"){if(!bt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}D(e,200,nu());return}if(t.method==="POST"&&r.pathname==="/pair/reset"){if(!bt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}Re.reset(),D(e,200,{ok:!0});return}if(t.method==="POST"&&r.pathname==="/shutdown"){if(!bt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}D(e,200,{status:"stopping"}),setTimeout(()=>ze("HTTP /shutdown request"),50);return}if(t.method==="POST"&&r.pathname==="/hook/claude/session-start"){if(!bt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}try{let s=await ii(t),i=t.headers[Zt],o=Array.isArray(i)?i[0]:i;ce.handleClaudeSessionStartHook(o,s),D(e,200,{ok:!0})}catch(s){D(e,400,{error:String(s)})}return}if(t.method==="POST"&&r.pathname==="/hook/claude/permission-request"){if(!bt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}try{let s=await ii(t),i=t.headers[Zt],o=Array.isArray(i)?i[0]:i,a=await ce.handleClaudePermissionHook(o,s);D(e,200,a)}catch(s){D(e,400,{error:String(s)})}return}if(t.method==="POST"&&r.pathname==="/pair/create"){try{let s=await ii(t);if(s.daemonId!==F.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){D(e,400,{error:"invalid_pair_request"});return}if(!Re.consumeWindow(s.pairNonce)){D(e,401,{error:"pair_window_expired"});return}let o=Re.issuePairToken(s.deviceId,s.deviceName),a=Tt();D(e,200,{daemonId:F.daemonId,displayName:F.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:F.port,deviceId:s.deviceId,pairToken:o})}catch(s){D(e,400,{error:String(s)})}return}let n=jc(t.headers.authorization,r.searchParams.get("token"));if(!Gc(n,_.legacyToken,(s,i)=>Re.validateAnyPairToken(s,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(r.pathname==="/file"){let s=r.searchParams.get("path");if(!s){e.writeHead(400),e.end("Missing path parameter");return}try{let i=nn(s);if(!(await(0,Ge.stat)(i)).isFile()){e.writeHead(404),e.end("Not a file");return}let a=(0,dn.extname)(i).toLowerCase(),c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".pdf":"application/pdf"}[a]||"application/octet-stream",u=await(0,Ge.readFile)(i);e.writeHead(200,{"Content-Type":c,"Content-Length":u.length}),e.end(u)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${ft}`)}),ne=new Nn.default({server:cr});cr.on("connection",t=>{un.add(t),t.on("close",()=>{un.delete(t)})});ne.on("connection",(t,e)=>{let n=new URL(e.url??"/",`http://localhost:${_.port}`).searchParams.get("token");if(n&&ri(n,_.legacyToken))Pe.set(t,{authMode:"query_token"}),b.increment("ws.auth.success",{mode:"query_token"}),ce.prewarmCaches();else if(n){let s=Re.validateAnyPairToken(n);if(s)Pe.set(t,{authMode:"query_token",deviceId:s.deviceId}),b.increment("ws.auth.success",{mode:"query_token"}),ce.prewarmCaches();else{b.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}}lr.info({clients:ne.clients.size},"client connected"),b.increment("ws.connect"),b.gauge("ws.clients",ne.clients.size),w.emit("ws.connect",{clients:ne.clients.size,authMode:Pe.get(t)?.authMode??"pending",deviceId:Pe.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(Xc(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(!Pe.has(t)){if(o.action==="auth.hello"&&o.daemonId===F.daemonId&&Re.validatePairToken(o.deviceId,o.pairToken)){Pe.set(t,{authMode:"auth_hello",deviceId:o.deviceId}),b.increment("ws.auth.success",{mode:"auth_hello"}),ce.prewarmCaches(),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:F.daemonId,displayName:F.displayName}}));return}if(o.action==="auth.hello"){b.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}b.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)w.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?j.error:a.level==="warn"?j.warn:j.info).call(j,{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 em(o.path);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=Pe.get(t);Zs(i,{deviceId:a?.deviceId,registerToken:Js,unregisterToken:Ks,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=Pe.get(t);Zs(i,{deviceId:a?.deviceId,registerToken:Js,unregisterToken:Ks,respond:l=>t.send(JSON.stringify(l))});return}await ce.handle(t,o)}catch(i){lr.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{lr.info({clients:ne.clients.size,code:s},"client disconnected"),b.increment("ws.disconnect"),b.increment("ws.disconnect.code",{code:String(s)}),b.gauge("ws.clients",ne.clients.size),w.emit("ws.disconnect",{clients:ne.clients.size,code:s}),ce.removeClient(t)}),t.on("error",s=>{lr.error({error:s.message},"websocket error")})});function oi(){for(let t of un)try{t.destroy()}catch{}un.clear()}function su(){let t=Dl({auditPath:ct,stdoutLogPath:Fr,stderrLogPath:Ur,auditMaxBytes:_.auditMaxBytes,logMaxBytes:_.daemonLogMaxBytes});t.trimmedFiles>0&&j.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 tm(){xt||(xt=setInterval(su,_.storageHousekeepingIntervalMs),xt.unref())}function rm(){xt&&(clearInterval(xt),xt=null)}function ze(t,e=0){if(!Zc){Zc=!0,j.info({reason:t,exitCode:e},"shutting down"),w.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-ru)/1e3)}),b.stopPeriodicLog(),rm(),ce.shutdown();for(let r of ne.clients)try{r.close(1001,"Server shutting down"),r.terminate()}catch{}ne.close(r=>{r&&j.error({error:String(r)},"websocket close error")}),cr.close(r=>{if(r){j.error({error:String(r)},"http close error"),oi(),process.exit(1);return}oi(),process.exit(e)}),setTimeout(()=>{j.error("force exiting after shutdown timeout"),oi(),process.exit(e||1)},3e3).unref()}}ne.on("error",t=>{lr.error({error:t.message},"wss error")});cr.on("error",t=>{if(t.code==="EADDRINUSE"){let e=Oc(_.port).filter(r=>r.pid!==process.pid);j.error({port:_.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else j.error({error:String(t)},"server error");ze(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>ze("SIGINT"));process.once("SIGTERM",()=>ze("SIGTERM"));process.once("SIGHUP",()=>ze("SIGHUP"));process.once("SIGTTIN",()=>ze("SIGTTIN"));process.once("SIGTSTP",()=>ze("SIGTSTP"));process.on("uncaughtException",t=>{j.error({error:String(t),stack:t.stack},"uncaughtException"),w.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{j.error({reason:String(t)},"unhandledRejection"),w.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});cr.listen(_.port,async()=>{su(),w.emit("daemon.start",{port:_.port}),b.startPeriodicLog(),tm(),j.info({port:_.port,daemonId:F.daemonId,displayName:F.displayName,canonicalHost:Tt().canonicalHost,fallbackHosts:Tt().fallbackHosts,claudePath:_.claudePath,codexPath:_.codexPath,auditMaxBytes:_.auditMaxBytes,daemonLogMaxBytes:_.daemonLogMaxBytes,storageHousekeepingIntervalMs:_.storageHousekeepingIntervalMs,turnStallTimeoutMs:_.turnStallTimeoutMs},"daemon started");let t=Tt(),e=nu();Vt(`
82
+ `}function Wl(t,e){let n=(0,Xt.join)((0,Ul.tmpdir)(),`vibelet-claude-hooks-${process.pid}-${(0,ql.randomUUID)()}`);(0,Te.mkdirSync)(n,{recursive:!0});let r=(0,Xt.join)(n,"settings.json"),s=(0,Xt.join)(n,"session_hook_forwarder.cjs"),i=(0,Xt.join)(n,"permission_hook_forwarder.cjs");return(0,Te.writeFileSync)(s,wh(t,e),"utf8"),(0,Te.writeFileSync)(i,bh(t,e),"utf8"),(0,Te.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 Vn(t){if(t)try{(0,Te.rmSync)(t.dirPath,{recursive:!0,force:!0})}catch{}}var Q=L.child({module:"claude"}),Vl="claude-permission-denial:",Ih=/\u001B\[[0-?]*[ -/]*[@-~]/g;function Ah(){return process.env.VIBE_TEST!=="1"&&!process.argv.includes("--test")}function Ps(t){Ah()&&jn(`\x1B[33m\u26A1 [Vibelet] ${t}\x1B[0m
83
+ `)}function kh(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 xh(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function Th(t){if(typeof t=="string")return t;let e=kh(t);return e||(xh(t)?"":JSON.stringify(t))}function Eh(t){return/requested permissions|haven't granted/i.test(t)}function jl(t){return t.replace(Ih,"").replace(/\s+/g," ").trim()}function Ch(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function Ph(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 Rh(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Gl(t){let e=jl(t.resultText??""),n=(t.stderrLines??[]).map(jl).filter(Boolean).slice(-3),r=[e,...n].find(i=>!!i&&Ph(i));if(r)return Rh(r);let s=[e,...n].find(i=>!!i&&!Ch(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 Yn(t){return t.startsWith(Vl)}var en=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=v.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()}`),Q.info({sessionId:this.sessionId,cwd:e},"session initialized"),w.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e){let n=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];this.sessionId&&!this.sessionId.startsWith("pending_")&&n.push("--resume",this.sessionId),Vn(this.hookFiles),this.hookFiles=null,this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=Wl(this.hookPort,this.hookSecret),n.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="acceptEdits"&&n.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&n.push("--dangerously-skip-permissions");let r=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;Q.info({sessionId:this.sessionId,label:r,promptPreview:e.slice(0,50)},"running claude"),Ps(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.replayPhase=!0,this.proc=(0,$l.spawn)(v.claudePath,n,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv()}),this.proc.on("error",s=>{let i=s.message;s.code==="ENOENT"&&this.cwd&&!(0,zl.existsSync)(this.cwd)&&(i=`Working directory does not exist: ${this.cwd}`),Q.error({sessionId:this.sessionId,error:i,cwd:this.cwd},"spawn error"),w.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:i}),this.handler?.({type:"error",sessionId:this.sessionId,message:i})}),this.buffer="",this.proc.stdout.on("data",s=>{this.buffer+=s.toString();let i=this.buffer.split(`
85
+ `);this.buffer=i.pop();for(let o of i)if(o.trim())try{this.handleRaw(JSON.parse(o))}catch{Q.warn({sessionId:this.sessionId,linePreview:o.slice(0,100)},"failed to parse stdout line")}}),this.proc.stderr.on("data",s=>{let i=s.toString().trim();i&&(Q.debug({sessionId:this.sessionId,stderr:i},"stderr"),this.lastStderr.push(i),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",(s,i)=>{Q.info({sessionId:this.sessionId,exitCode:s,signal:i},"process exited");let o=this.interrupted;this.proc=null,Vn(this.hookFiles),this.hookFiles=null,this.interrupted=!1,o&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):s&&s!==0&&!this.sawFinalResult&&(Q.error({sessionId:this.sessionId,exitCode:s,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Gl({stderrLines:this.lastStderr,exitCode:s})})),this.exitHandler?.(s)})}respondApproval(e,n){if(Q.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return Q.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,Q.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),Q.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,Vn(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&&(Q.info({oldSessionId:this.sessionId,newSessionId:r},"session ID resolved"),w.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=Th(s.content);if(!i)continue;if(s.is_error===!0&&typeof s.tool_use_id=="string"&&Eh(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"&&(w.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){Ps("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Gl({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}.`;w.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:c}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${Vl}${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;Ps("Claude finished. Run `claude --continue` to continue on desktop."),w.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 Xl=require("child_process"),Zl=require("fs");var Rs=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();L.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},b=new Rs;var Yl=require("node:fs"),Ls=require("node:path"),Lh="@vibelet/cli";function Mh(t){try{let e=JSON.parse((0,Yl.readFileSync)(t,"utf8"));if(e.name===Lh&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function Nh(){return"0.1.6"}var ft=Nh();var x=L.child({module:"codex"});function Oh(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 Bh(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 ee(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function C(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function Dh(t){let e=C(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function Ms(t){return t?C(t.itemId)??C(t.id)??C(t.callId)??C(t.call_id):null}function Ns(t,e){let n={};for(let[r,s]of Object.entries(t))e.includes(r)||(n[r]=s);return n}function Ql(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function ec(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function Hh(t){if(!Array.isArray(t))return null;for(let e of t){let n=ee(e);if(!n)continue;let r=C(n.id),s=Array.isArray(n.options)?n.options.map(l=>ee(l)).filter(l=>!!l):[];if(!r||s.length===0)continue;let i=s.map(l=>C(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>Ql(l))??i[0],a=i.find(l=>ec(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:r,approveLabel:o,denyLabel:a}}return null}function Fh(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(s=>ee(s)).filter(s=>!!s).flatMap(s=>(Array.isArray(s.options)?s.options:[]).map(o=>ee(o)).filter(o=>!!o).map(o=>C(o.label)).filter(o=>!!o)),n=e.some(s=>Ql(s)),r=e.some(s=>ec(s));return n&&r}function Jl(t){let e=Dh(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:Ns(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:Ns(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=C(t.server),r=C(t.tool)??C(t.name);return r?{toolName:n?`mcp__${n}__${r}`:r,input:ee(t.arguments)??ee(t.input)??{}}:null}return null}function Uh(t){if(!Array.isArray(t))return"";for(let e of t){let n=ee(e);if(!n)continue;let r=C(n.question)??C(n.header);if(r)return r}return""}function Kl(t,e){return t==="autoApprove"?{approvalPolicy:"never",sandbox:"danger-full-access",sandboxPolicy:{type:"dangerFullAccess"}}:{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[e],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}}var Jn=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;approvalMode;cwd="";async start(e,n,r){this.approvalMode=r,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear();let s=v.codexPath,i,o=this.buildSpawnArgs();if(v.isTransientPath(s)){let c=v.execViaLoginShell("codex",o);i=c.command,o=c.args,x.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=s,x.info({spawnCmd:i,args:o},"spawning");w.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,Xl.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:v.buildSanitizedEnv()}),this.proc.on("error",c=>{let u=c.message;c.code==="ENOENT"&&e&&!(0,Zl.existsSync)(e)&&(u=`Working directory does not exist: ${e}`),x.error({error:u,cwd:e},"spawn error"),w.emit("driver.error",{agent:"codex",error:u})}),this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let u=this.buffer.split(`
87
+ `);this.buffer=u.pop();for(let d of u)if(d.trim())try{this.handleRaw(JSON.parse(d))}catch{x.warn({linePreview:d.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let u=c.toString().trim();u&&(x.debug({stderr:u},"stderr"),this.lastStderr.push(u),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{x.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&x.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear();for(let[,{reject:u}]of this.pending)u(new Error(`Codex process exited with code ${c}`));this.pending.clear(),this.exitHandler?.(c),c&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${c}`})});let a=b.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:ft},capabilities:{experimentalApi:!0}}),a(),this.rpcNotify("initialized",{});let l=Kl(this.approvalMode,e);if(n){let c=await this.rpc("thread/resume",{threadId:n,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,persistExtendedHistory:!0});this.threadId=c?.thread?.id??n,x.info({threadId:this.threadId},"thread resumed"),w.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let c=await this.rpc("thread/start",{cwd:e,approvalPolicy:l.approvalPolicy,sandbox:l.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=c?.thread?.id??c?.threadId??"",x.info({threadId:this.threadId},"thread created"),w.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}buildSpawnArgs(){return["app-server","--listen","stdio://"]}sendPrompt(e){let n=Kl(this.approvalMode,this.cwd||process.cwd());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:n.approvalPolicy,sandboxPolicy:n.sandboxPolicy}).then(r=>x.debug({resultPreview:JSON.stringify(r).slice(0,200)},"turn/start result")).catch(r=>{x.error({threadId:this.threadId,error:r.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:r.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=Bh(e);n&&this.approvalRequests.set(e.requestId,n)}interrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}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();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=b.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()})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
90
+ `)}writeServerRequestError(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:e,error:{code:-32601,message:n}})+`
91
+ `)}resolveToolContext(e){let n=ee(e?.item)??e??null,r=Ms(n);if(!r)return null;let s=n?Jl(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?Ns(e,["threadId","turnId",...n]):{}}queueApprovalRequest(e,n,r){if(this.approvalRequests.set(e,n),w.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:Oh(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"])},C(r?.reason)??C(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"])},C(r?.reason)??C(r?.description)??"");return}if(e==="item/tool/requestUserInput"){let o=r?.questions;if(!Fh(o)){x.warn({threadId:this.threadId,rpcId:n},"unsupported requestUserInput request"),this.writeServerRequestError(n,"Unsupported interactive request from Codex");return}let a=Hh(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"])},Uh(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,[])},C(r?.reason)??C(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,[])},C(r?.reason)??C(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=ee(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=ee(r?.item),i=Ms(s),o=s?Jl(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=ee(r?.item)??r,i=Ms(s);i&&this.toolContextByCallId.delete(i);break}case"turn/completed":{let s=ee(r?.usage),i=s?{inputTokens:Number(s.input_tokens??s.inputTokens??0),outputTokens:Number(s.output_tokens??s.outputTokens??0)}:void 0;x.info({threadId:this.threadId},"turn completed"),w.emit("session.done",{agent:"codex",sessionId:this.threadId,usage:i}),this.handler&&this.handler({type:"session.done",sessionId:this.threadId,usage:i});break}default:n&&x.debug({method:n},"unhandled notification");break}}};var B=require("fs/promises"),Gs=require("fs"),$s=require("readline"),E=require("path"),me=require("os");var qh=new Set(["New session","Resumed session","Untitled session"]),Wh=["<environment_context>","<local-command-caveat>","<local-command-stdout>","<local-command-stderr>","<command-name>","<command-message>","<command-args>","# AGENTS.md instructions for "];function jh(t){return t.replace(/\s+/g," ").trim()}function Kn(t){return typeof t!="string"?void 0:jh(t)||void 0}function tc(t){let e=Kn(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 pt(t){let e=Kn(t);return!e||qh.has(e)||tc(e)}function Gh(t){for(let e of t.replace(/\r/g,"").split(`
92
+ `)){let n=Kn(e);if(n&&!$h(n)&&!zh(n))return n}}function $h(t){return Wh.some(e=>t.startsWith(e))}function zh(t){let e=t.replace(/^['"`]+/,"").replace(/['"`\\]+$/,"").trim();return!!(!e||/^(\/|~\/|\.\/|\.\.\/)/.test(e)||/^[A-Za-z]:\\/.test(e))}function Vh(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 Os(t,e=80){if(typeof t!="string")return;let n=Gh(t);if(!n)return;let r=Vh(n),i=(r>0?n.slice(0,r):n).replace(/[。!?;.!?;]+$/gu,"").trim();if(!(!i||tc(i)))return i.length<=e?i:`${i.slice(0,Math.max(1,e-3)).trimEnd()}...`}function je(t,e){for(let n of t){let r=Kn(n);if(!(!r||pt(r)))return r}return Os(e)}var rc=require("child_process"),ht=require("fs/promises"),Ee=require("path"),Bs=require("os"),sc=require("util");var Yh=(0,sc.promisify)(rc.execFile),Jh=15e3,tn=null;function Zn(){tn=null}function Kh(t){return t.replace(/^['"]|['"]$/g,"")}function Xh(t){return(t.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(Kh)}function Ds(t){let e=Xh(t);for(let n=0;n<e.length;n+=1){let r=e[n],s=(0,Ee.basename)(r);if(s==="claude"||s==="codex")return{agent:s,args:e.slice(n+1)}}return null}function Zh(t,e){let n=Ds(e);if(!n||n.agent!==t)return null;let{args:r}=n;if(t==="claude"){for(let s=0;s<r.length;s+=1){let i=r[s];if((i==="--resume"||i==="--session-id")&&r[s+1]&&!r[s+1].startsWith("-"))return r[s+1];if(i.startsWith("--resume="))return i.slice(9);if(i.startsWith("--session-id="))return i.slice(13)}return null}if(r[0]!=="resume")return null;for(let s=1;s<r.length;s+=1){let i=r[s];if(!i.startsWith("-"))return i}return null}function Xn(t){switch(t){case"high":return 3;case"medium":return 2;default:return 1}}function Qh(t,e){return t==="claude"?e.includes("/.claude/projects/")&&!e.includes("/subagents/"):e.includes("/.codex/sessions/")}function eg(t,e){let n=Ds(e);return!n||n.agent!==t?!1:n.args.includes("--continue")||n.args.includes("-c")}function tg(t){let e=Zh(t.agent,t.command);if(e)return{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:e,confidence:"high"};let n=[...new Set(t.sessionFiles)].filter(s=>Qh(t.agent,s));if(n.length!==1)return null;let r=gt(t.agent,n[0]);return r?{agent:t.agent,pid:t.pid,cwd:t.cwd,command:t.command,sessionId:r,confidence:"medium",sessionFilePath:n[0]}:null}function ng(t,e){let n=t,r=e;return(Xn(e.confidence)>Xn(t.confidence)||Xn(e.confidence)===Xn(t.confidence)&&e.pid<t.pid)&&(n=e,r=t),{...n,cwd:n.cwd||r.cwd,title:n.title??r.title,sessionFilePath:n.sessionFilePath??r.sessionFilePath}}function rg(t){let e=new Map;for(let n of t){let r=`${n.agent}:${n.sessionId}`,s=e.get(r);e.set(r,s?ng(s,n):n)}return[...e.values()]}async function Hs(t,e){try{let{stdout:n}=await Yh(t,e,{maxBuffer:8388608});return n}catch{return""}}async function nc(t){if(!t.sessionFilePath)return t;let e=await nn(t.sessionFilePath,t.agent);return e?{...t,cwd:t.cwd||e.cwd,title:t.title??e.title}:null}async function sg(t){return(await Hs("lsof",["-a","-p",String(t),"-d","cwd","-Fn"])).split(`
93
+ `).find(r=>r.startsWith("n"))?.slice(1).trim()??""}async function ig(t){let n=(await Hs("lsof",["-p",String(t),"-Fn"])).split(`
94
+ `).filter(r=>r.startsWith("n")).map(r=>r.slice(1).trim()).filter(r=>r.endsWith(".jsonl")?r.includes("/.claude/projects/")||r.includes("/.codex/sessions/"):!1);return[...new Set(n)]}async function og(){return(await Hs("pgrep",["-fal","(^|/)(claude|codex)( |$)|claude app-server|codex app-server"])).split(`
95
+ `).map(e=>e.trim()).filter(Boolean).map(e=>{let n=e.match(/^(\d+)\s+(.*)$/);if(!n)return null;let r=Number(n[1]),s=n[2],i=Ds(s);return!Number.isFinite(r)||!i?null:{pid:r,command:s,agent:i.agent}}).filter(e=>!!e)}async function ag(){let t=await og();return Promise.all(t.map(async e=>({pid:e.pid,agent:e.agent,command:e.command,cwd:await sg(e.pid),sessionFiles:await ig(e.pid)})))}function lg(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function cg(t,e){if(!e)return null;try{if(t==="claude"){let o=(0,Ee.join)((0,Bs.homedir)(),".claude","projects",lg(e)),l=(await(0,ht.readdir)(o).catch(()=>[])).filter(f=>f.endsWith(".jsonl"));if(l.length===0)return null;let c=null;if(await Promise.all(l.map(async f=>{let p=await(0,ht.stat)((0,Ee.join)(o,f)).catch(()=>null);p&&(!c||p.mtimeMs>c.mtimeMs)&&(c={name:f,mtimeMs:p.mtimeMs})})),!c)return null;let u=(0,Ee.join)(o,c.name),d=gt(t,u);return d?{sessionId:d,filePath:u}:null}let n=(0,Ee.join)((0,Bs.homedir)(),".codex","sessions"),r=null;async function s(o){let a=await(0,ht.readdir)(o,{withFileTypes:!0}).catch(()=>[]);for(let l of a){let c=(0,Ee.join)(o,l.name);if(l.isDirectory())await s(c);else if(l.name.endsWith(".jsonl")){let u=await(0,ht.stat)(c).catch(()=>null);if(!u||r&&u.mtimeMs<=r.mtimeMs)continue;let d=await nn(c,t);if(!d||d.cwd!==e)continue;r={path:c,mtimeMs:u.mtimeMs,sessionId:d.sessionId}}}}await s(n);let i=r;return i?{sessionId:i.sessionId,filePath:i.path}:null}catch{return null}}async function ic(){if(tn&&Date.now()<tn.expiresAt)return tn.value;let t=await ag(),e=await Promise.all(t.map(async r=>{let s=tg(r);if(s)return nc(s);if(eg(r.agent,r.command))return null;let i=await cg(r.agent,r.cwd);return i?nc({agent:r.agent,pid:r.pid,cwd:r.cwd,command:r.command,sessionId:i.sessionId,confidence:"low",sessionFilePath:i.filePath}):null})),n=rg(e.filter(r=>r!==null));return tn={value:n,expiresAt:Date.now()+Jh},n}var ac=L.child({module:"inventory"}),mt={daemonActive:3,externalRunning:2,idle:1},oc={high:3,medium:2,low:1};function lc(t,e){return e.lastActivityAt.localeCompare(t.lastActivityAt)||t.sessionId.localeCompare(e.sessionId)}function ug(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||mt[e.runtime.state]-mt[t.runtime.state]||lc(t,e)}function dg(t,e){return mt[e.state]>mt[t.state]?e:mt[e.state]<mt[t.state]?t:oc[e.confidence]>oc[t.confidence]?e:t}function fg(t,e){return t?e?t.localeCompare(e)<=0?t:e:t:e}function pg(t,e){return t?e?t.localeCompare(e)>=0?t:e:t:e}function hg(t,e){return e?t?!(pt(e)&&!pt(t)):!0:!1}function Fs(t="high",e="resumeSession"){return{state:"idle",confidence:t,resumeMode:e}}function gg(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:["record"],runtime:Fs(),managed:t.managed,approvalMode:t.approvalMode}}function mg(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",pid:t.pid,command:t.command}}}function yg(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 Sg(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=hg(s.title,n.title)?n.title:s.title,o=n.cwd||s.cwd,a=dg(s.runtime,n.runtime),l=s.sources.slice();for(let f of n.sources)l.includes(f)||l.push(f);let c=n.sources.includes("process"),u=s.sources.includes("process")&&!s.sources.includes("daemon"),d=c?s.lastActivityAt:u?n.lastActivityAt:pg(s.lastActivityAt,n.lastActivityAt);t.set(r,{...s,cwd:o,title:i,createdAt:fg(s.createdAt,n.createdAt),lastActivityAt:d,sources:l,runtime:a,managed:s.managed||n.managed,approvalMode:n.approvalMode??s.approvalMode})}}function vg(...t){let e=new Map;for(let n of t)Sg(e,n);return[...e.values()]}function _g(t,e,n,r,s){let i=r?.toLowerCase(),o=t.filter(a=>{if(e&&a.agent!==e||n&&a.cwd!==n)return!1;if(i){let l=(a.title??"").toLowerCase(),c=(a.cwd??"").toLowerCase(),u=l.includes(i)||c.includes(i),d=s?.has(a.sessionId)??!1;if(!u&&!d)return!1}return!0});return r&&ac.info({total:t.length,filtered:o.length,search:r,contentMatchIds:s?.size??0},"filter applied"),o}function wg(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 bg(t,e,n,r,s,i,o){let a=i?1/0:Math.max(1,e||50),l=vg(t.sessionRecords.map(gg),t.scannedSessions,t.runningSessions.map(S=>mg(S,t.scannedAt)),t.activeSessions.map(yg)),c=t.deletedSessionIds?.size?l.filter(S=>!t.deletedSessionIds?.has(S.sessionId)):l,u=_g(c,r,s,i,o),d=u.filter(S=>S.runtime.state!=="idle"||S.managed).sort(ug),f=u.filter(S=>S.runtime.state==="idle"&&!S.managed).sort(lc),p=wg(f,n),h=f.slice(p,p+a),m=p+h.length<f.length&&h.length>0?{lastActivityAt:h[h.length-1].lastActivityAt,sessionId:h[h.length-1].sessionId}:void 0;return{sessions:n?h:[...d,...h],nextCursor:m}}async function Qn(t){let e=new Date().toISOString(),[n,r,s]=await Promise.all([rn(t.agent,t.cwd),ic(),t.search?cc(t.search,t.agent):Promise.resolve(void 0)]);return t.search&&ac.info({search:t.search,contentMatches:s?.size??0,scanned:n.length,records:t.sessionRecords.length,active:t.activeSessions.length},"search results"),bg({activeSessions:t.activeSessions,sessionRecords:t.sessionRecords,scannedSessions:n,runningSessions:r,scannedAt:e,deletedSessionIds:t.deletedSessionIds},t.limit,t.cursor,t.agent,t.cwd,t.search,s)}var Ce=L.child({module:"scanner"});function hc(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 gc=3e4,qs=hc(gc),Ws=hc(gc),er=8;function nr(){qs.clear(),Ws.clear()}function js(t){return t.replace(/[^a-zA-Z0-9]/g,"-")}async function tr(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*mc(t,e){let n=0,r=0;for(;n<t.length&&r<e;){let s=t.indexOf(`
96
+ `,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 Us=512*1024;async function yc(t,e){if(e<=Us)return(0,B.readFile)(t,"utf-8");let n=await(0,B.open)(t,"r");try{let r=Buffer.alloc(Us),{bytesRead:s}=await n.read(r,0,Us,0);return r.toString("utf-8",0,s)}finally{await n.close()}}function zs(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 Sc(t){return t?.type==="response_item"&&t.payload?.type==="message"&&t.payload.role==="user"?zs(t.payload.content):t?.type==="event_msg"&&t.payload?.type==="user_message"&&typeof t.payload.message=="string"?t.payload.message:""}function Vs(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 Ig=["<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 Ag(t,e){if(t?.isMeta===!0)return!0;let n=e.trim();return n?Ig.some(r=>n.startsWith(r)):!1}function Ys(t){if(t?.type!=="user"||t.message?.role!=="user")return"";let e=Vs(t.message.content);return Ag(t,e)?"":e}function vc(t){let e=t.trim();return e.startsWith("# AGENTS.md instructions for ")||e.startsWith("<environment_context>")}function _c(t,e="scanner"){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,sources:[e],runtime:Fs()}}function gt(t,e){let n=(0,E.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 kg(t,e){let n=await yc(t,e),r=mc(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=je([u.customTitle,u.summary])),!l){let d=Ys(u),f=je([],d);f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||gt("claude",t)||(0,E.basename)(t,".jsonl"),cwd:s,title:o??l??je([],a)}:null}async function xg(t,e){let n=await yc(t,e),r=mc(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=je([u.payload?.title,u.title])),!l){let d=Sc(u),f=d&&!vc(d)?je([],d):void 0;f&&(a=d,l=f)}if(s&&(o||l))break}return s?{sessionId:i||gt("codex",t)||(0,E.basename)(t,".jsonl"),cwd:s,title:o??l??je([],a)}:null}async function nn(t,e){let n=await(0,B.stat)(t).catch(()=>null);if(!n)return null;try{let r=n.size;if(e==="claude"){let i=await kg(t,r);return i?{sessionId:i.sessionId,agent:e,cwd:i.cwd,title:i.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}let s=await xg(t,r);return s?{sessionId:s.sessionId,agent:e,cwd:s.cwd,title:s.title,createdAt:new Date(n.birthtimeMs).toISOString(),lastActivityAt:new Date(n.mtimeMs).toISOString(),filePath:t}:null}catch{return null}}async function uc(t){let e=(0,E.join)((0,me.homedir)(),".claude","projects");try{let n;t?n=[js(t)]:n=(await(0,B.readdir)(e,{withFileTypes:!0})).filter(a=>a.isDirectory()).map(a=>a.name);let r=[];for(let o of n){let a=(0,E.join)(e,o),l=await(0,B.readdir)(a).catch(()=>[]);for(let c of l)c.endsWith(".jsonl")&&r.push((0,E.join)(a,c))}return(await tr(r,er,o=>nn(o,"claude"))).filter(o=>o!==null).map(o=>_c(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(n){return Ce.warn({error:String(n)},"failed to list claude sessions"),[]}}async function dc(t){let e=(0,E.join)((0,me.homedir)(),".codex","sessions");try{let n=await(0,B.readdir)(e).catch(()=>[]),r=[];for(let o of n){let a=(0,E.join)(e,o),l=await(0,B.readdir)(a).catch(()=>[]);for(let c of l){let u=(0,E.join)(a,c),d=await(0,B.readdir)(u).catch(()=>[]);for(let f of d){let p=(0,E.join)(u,f),h=await(0,B.readdir)(p).catch(()=>[]);for(let g of h)g.endsWith(".jsonl")&&r.push((0,E.join)(p,g))}}}return(await tr(r,er,o=>nn(o,"codex"))).filter(o=>o!==null).filter(o=>!t||o.cwd===t).map(o=>_c(o)).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt))}catch(n){return Ce.warn({error:String(n)},"failed to list codex sessions"),[]}}async function rn(t,e){let r=`list:${(0,me.homedir)()}:${t??"all"}:${e??""}`,s=qs.get(r);if(s)return s;let i;if(t==="claude")i=await uc(e);else if(t==="codex")i=await dc(e);else{let[o,a]=await Promise.all([uc(e),dc(e)]);i=[...o,...a].sort((l,c)=>c.lastActivityAt.localeCompare(l.lastActivityAt))}return qs.set(r,i),i}async function cc(t,e){let r=`search:${(0,me.homedir)()}:${t}:${e??"all"}`,s=Ws.get(r);if(s)return s;let i=new Set,o=t.toLowerCase();async function a(){let c=(0,E.join)((0,me.homedir)(),".claude","projects");try{let u=await(0,B.readdir)(c,{withFileTypes:!0}),d=[];for(let p of u){if(!p.isDirectory())continue;let h=(0,E.join)(c,p.name),g=await(0,B.readdir)(h).catch(()=>[]);for(let m of g)m.endsWith(".jsonl")&&d.push((0,E.join)(h,m))}let f=await tr(d,er,p=>fc(p,o,"claude"));for(let p of f)p&&i.add(p)}catch(u){Ce.warn({error:String(u)},"failed to search claude files")}}async function l(){let c=(0,E.join)((0,me.homedir)(),".codex","sessions");try{let u=[];async function d(p){let h=await(0,B.readdir)(p,{withFileTypes:!0}).catch(()=>[]);for(let g of h){let m=(0,E.join)(p,g.name);g.isDirectory()?await d(m):g.name.endsWith(".jsonl")&&u.push(m)}}await d(c);let f=await tr(u,er,p=>fc(p,o,"codex"));for(let p of f)p&&i.add(p)}catch(u){Ce.warn({error:String(u)},"failed to search codex files")}}return e==="claude"?await a():e==="codex"?await l():await Promise.all([a(),l()]),Ws.set(r,i),i}async function fc(t,e,n){let r=(0,Gs.createReadStream)(t,{encoding:"utf-8"}),s=(0,$s.createInterface)({input:r,crlfDelay:1/0}),i=n==="claude"?Tg:Eg,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||gt(n,t):null}function Tg(t){return t?.type==="user"&&t.message?.role==="user"?Ys(t):t?.type==="assistant"&&t.message?.role==="assistant"?Vs(t.message.content):""}function Eg(t){if(t?.type==="response_item"&&t.payload?.type==="message"){let n=t.payload.role;if(n==="user"||n==="assistant")return zs(t.payload.content)}let e=Sc(t);return e||""}async function pc(t,e){let n=(0,Gs.createReadStream)(t,{encoding:"utf-8"}),r=(0,$s.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 sn(t,e,n){let r=[];if(e==="claude"){let s=(0,E.join)((0,me.homedir)(),".claude","projects");try{let i=n?[js(n)]:[],o=await(0,B.readdir)(s).catch(()=>[]),a=n?[...i,...o.filter(l=>l!==js(n))]:o;for(let l of a){let c=(0,E.join)(s,l,`${t}.jsonl`);try{if(await pc(c,u=>{if(u.type==="user"&&u.message?.role==="user"){let d=Ys(u);d&&r.push({role:"user",content:d})}else if(u.type==="assistant"&&u.message?.role==="assistant"){let d=Vs(u.message.content);d&&r.push({role:"assistant",content:d})}}),r.length>0)break}catch(u){u.code!=="ENOENT"&&Ce.warn({error:String(u)},"failed to read claude session file")}}}catch(i){Ce.warn({error:String(i)},"failed to read claude session history")}}else if(e==="codex"){let s=(0,E.join)((0,me.homedir)(),".codex","sessions");try{let i=await wc(s,t);i&&await pc(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=zs(o.payload.content);l&&(a==="user"&&vc(l)||r.push({role:a,content:l}))})}catch(i){Ce.warn({error:String(i)},"failed to read codex session history")}}return r}async function wc(t,e){try{let n=await(0,B.readdir)(t,{withFileTypes:!0});for(let r of n){let s=(0,E.join)(t,r.name);if(r.isDirectory()){let i=await wc(s,e);if(i)return i}else if(r.name.includes(e)&&r.name.endsWith(".jsonl"))return s}}catch(n){Ce.warn({error:String(n)},"failed to walk codex sessions dir")}return null}var yt=require("fs"),Ac=require("path");var Cg=500,bc=200;function Pg(t){if(!Array.isArray(t))return[];let e=t.filter(n=>typeof n=="string"&&n.length>0);return e.length<=bc?e:e.slice(-bc)}function Rg(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 Lg(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 Ic(t){return{...t,lastActivityAt:t.lastActivityAt??t.createdAt,acceptedClientMessageIds:Pg(t.acceptedClientMessageIds),pendingApproval:Lg(t.pendingApproval)}}function Mg(t){if(Array.isArray(t))return{records:t.map(Ic),deletedSessionIds:[]};if(t&&typeof t=="object"){let e=t;return{records:Array.isArray(e.records)?e.records.map(Ic):[],deletedSessionIds:Rg(e.deletedSessionIds)}}return{records:[],deletedSessionIds:[]}}var rr=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()},Cg)}loadFromDisk(){try{let e=(0,yt.readFileSync)(Fn,"utf-8");return Mg(JSON.parse(e))}catch{}return{records:[],deletedSessionIds:[]}}saveToDisk(){(0,yt.mkdirSync)((0,Ac.dirname)(Fn),{recursive:!0}),(0,yt.writeFileSync)(Fn,JSON.stringify({records:this.records,deletedSessionIds:[...this.deletedSessionIds]},null,2))}};var kc=require("path"),xc=require("os");function sr(t){return t=t.replace(/^~/,"~"),t.startsWith("~/")||t==="~"?(0,kc.join)((0,xc.homedir)(),t.slice(2)):t}var St=require("fs"),Tc=require("path");function Ng(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 Og(t){try{let e=(0,St.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(Ng):[]}catch{return[]}}function on(t,e){(0,St.mkdirSync)((0,Tc.dirname)(t),{recursive:!0}),(0,St.writeFileSync)(t,JSON.stringify(e,null,2)+`
97
+ `,"utf8")}var ir=class{constructor(e=kl){this.pushSubscriptionsPath=e;this.records=Og(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)],on(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,on(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,on(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&&on(this.pushSubscriptionsPath,this.records)}reset(){this.records=[],on(this.pushSubscriptionsPath,this.records)}};var $=L.child({module:"push"}),Bg="https://exp.host/--/api/v2/push/send",Dg="https://exp.host/--/api/v2/push/getReceipts",Hg=[0,1e3,3e3],an=new ir;function Fg(t){return new Promise(e=>{setTimeout(e,t)})}function Ec(t){return t==="DeviceNotRegistered"}function Ug(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 qg(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 Wg(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 jg(t,e,n,r){let s=new Map(t);for(let i of Hg){if(s.size===0)return;i>0&&await n(i);let o;try{o=await e(Dg,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:[...s.keys()]})})}catch(u){$.error({error:String(u),count:s.size},"push receipt request failed");return}if(!o.ok){$.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){$.error({count:s.size},"push receipt response was unreadable");return}let{pendingTicketIds:l,receiptErrors:c}=Wg(a,s);for(let{token:u,receipt:d}of c){let f=d.details?.error;if($.error({token:u,message:d.message,details:d.details,receiptStatus:d.status},"push receipt rejected"),Ec(f)){let p=r.unregisterToken(u);$.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&&$.warn({pendingReceipts:s.size},"push receipts still pending after polling")}function Gg(t){let e=t?.pushStore??an,n=t?.fetchImpl??globalThis.fetch,r=t?.sleepImpl??Fg;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}));try{let u=await n(Bg,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});if(!u.ok){$.error({status:u.status,statusText:u.statusText},"push send failed");return}let d=await u.json().catch(()=>null);if(!d){$.error({count:c.length},"push send returned unreadable response");return}let{successfulTokens:f,ticketErrors:p}=Ug(d,l),h=qg(d,l);for(let{token:g,ticket:m}of p){let S=m.details?.error;if($.error({token:g,message:m.message,details:m.details,ticketStatus:m.status},"push ticket rejected"),Ec(S)){let U=e.unregisterToken(g);$.info({token:g,errorCode:S,removed:U},"push token removed after ticket rejection")}}f.length>0&&($.debug({count:f.length},"push sent"),e.markSent(f)),h.size>0&&await jg(h,n,r,e)}catch(u){$.error({error:String(u)},"push send error")}}}function Js(t,e){an.register(t,e),$.info({deviceId:t,token:e,total:an.count()},"push token registered")}function Ks(t,e){let n=an.unregister(t,e);$.info({deviceId:t,token:e,total:an.count(),removed:n},"push token unregistered")}var Cc=Gg();var _=L.child({module:"manager"}),$g="Done.",zg="Approval required",Pc=180,ar=200;function or(...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>ar&&e.splice(0,e.length-ar));return e}function ce(t){return{sessionId:t.sessionId,agent:t.agent,cwd:t.cwd,approvalMode:t.approvalMode,acceptedClientMessageIds:or(t.acceptedClientMessageIds),pendingApproval:t.agent==="codex"?t.pendingApproval:void 0,title:t.title,createdAt:t.createdAt,lastActivityAt:t.lastActivityAt,managed:t.managed}}function Rc(t){let e=t.pendingApproval?.requestId;return typeof e=="string"&&Yn(e)}function Lc(t,e,n){return{sessionId:t,agent:e,...n}}function Vg(t){return t.startsWith(Cs)}function Mc(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 lr=class{constructor(e=Cc){this.pushSender=e;this.startIdleSweep()}sessions=new Map;claudeHookSessions=new Map;store=new rr;idleSweepInterval=null;startIdleSweep(){v.idleTimeoutMs<=0&&v.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=v.idleTimeoutMs,r=v.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"),b.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"),b.increment("driver.stall_timeout",{agent:o.agent}),w.emit("driver.stall_timeout",{sessionId:o.sessionId,agent:o.agent,idleMs:a}),o.isResponding=!1,o.currentReplyText="",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.`}),o.driver.stop(),o.active=!1,o.driver=null,this.updateGauges(),this.touchSession(o.sessionId);continue}o.pendingApproval||n<=0||a<n||(_.info({sessionId:o.sessionId,agent:o.agent,idleMs:a,timeoutMs:n},"stopping idle driver"),b.increment("driver.idle_timeout",{agent:o.agent}),w.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))}}bindDriverLifecycle(e,n,r,s){e.driver?.onMessage(i=>{if(_.debug({agent:n,context:r,msgType:i.type,sessionId:e.sessionId},"driver message received"),i.type!=="response"&&i.sessionId&&i.sessionId!==e.sessionId&&!this.sessions.has(i.sessionId)&&this.remapSessionId(e,i.sessionId,s),(i.type==="session.done"||i.type==="session.interrupted")&&(e.isResponding=!1,(i.type==="session.interrupted"||!Rc(e))&&(e.pendingApproval=void 0)),i.type==="approval.request"){if(n==="codex"&&e.approvalMode==="autoApprove"){if(e.driver?.respondApproval(i.requestId,!0)??!1){w.emit("approval.response",{sessionId:e.sessionId,requestId:i.requestId,approved:!0}),e.pendingApproval=void 0,e.isResponding=!0,this.touchSession(e.sessionId);return}_.warn({sessionId:e.sessionId,requestId:i.requestId},"failed to auto-approve codex request; falling back to pending approval flow")}e.isResponding=!1,e.pendingApproval={requestId:i.requestId,toolName:i.toolName,input:i.input,description:i.description,...i.approvalContext?{approvalContext:i.approvalContext}:{}},this.pushSender(zg,this.buildPushBody(`${e.title||e.sessionId}: ${i.description||i.toolName}`),{sessionId:e.sessionId,agent:e.agent,requestId:i.requestId})}n==="claude"&&i.type==="approval.request"&&Yn(i.requestId)&&(e.lastUserMessage?e.syntheticApprovalRetries[i.requestId]={message:e.lastUserMessage,toolName:i.toolName}:_.warn({sessionId:e.sessionId,requestId:i.requestId},"missing lastUserMessage for synthetic approval retry")),this.touchSession(e.sessionId,i.type!=="text.delta"),this.broadcast(e.sessionId,i),(i.type==="session.done"||i.type==="session.interrupted")&&e.bufferedPrompts.length>0&&this.flushBufferedPrompt(e)}),e.driver?.onExit?.(i=>{_.info({agent:n,context:r,exitCode:i,sessionId:e.sessionId},"driver exited"),w.emit("driver.exit",{sessionId:e.sessionId,agent:n,exitCode:i}),b.increment("driver.exit",{agent:n,abnormal:i&&i!==0?"true":"false"});let o=!!(e.pendingApproval&&(e.agent==="codex"||i===0&&Rc(e)));this.resolvePendingClaudeHookApprovals(e),e.active=!1,e.driver=null,e.isResponding=!1,e.currentReplyText="",o||(e.pendingApproval=void 0),this.updateGauges(),this.touchSession(e.sessionId)})}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(ce(e)),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),e.driver.sendPrompt(r),!0):!1}startPendingCodexSession(e,n){if(e.agent!=="codex"||!e.driver)return;let r=e.driver,s=e.sessionId,i=e.startupToken,o=b.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),_.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){if(e!=="claude"||!(n instanceof en))return;let s=r??(0,Xs.randomUUID)().replace(/-/g,"");return n.configureHookBridge(v.port,s),s}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=Qt){for(let r of e.pendingClaudeHookApprovals.values())r.resolve(n);e.pendingClaudeHookApprovals.clear(),e.pendingApproval&&Vg(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"),Qt;if(r.approvalMode==="autoApprove")return Mc(!0);let i=(typeof n.tool_name=="string"?n.tool_name:typeof n.toolName=="string"?n.toolName:"").trim();if(!i)return Qt;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=`${Cs}${l.trim()||(0,Xs.randomUUID)()}`,u=r.pendingClaudeHookApprovals.get(c);if(u)return u.promise;let d=`Claude requested permissions to use ${i}.`,f,p=new Promise(h=>{f=h});return r.pendingClaudeHookApprovals.set(c,{requestId:c,promise:p,resolve:h=>{r.pendingClaudeHookApprovals.delete(c),f(h)}}),r.pendingApproval={requestId:c,toolName:i,input:a,description:d},w.emit("approval.request",{agent:"claude",sessionId:r.sessionId,toolName:i}),this.touchSession(r.sessionId),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=or(r?.acceptedClientMessageIds),p=r?"memory":"client",h=this.store.find(e);if(h)i=h.agent,o=h.cwd||o,a=h.approvalMode??a,l=h.pendingApproval??l,c=h.title||c,u=h.createdAt||u,d=h.lastActivityAt||d,f=or(h.acceptedClientMessageIds,f),p="record";else if(!r){let m=(await rn(n??i)).find(S=>S.sessionId===e);m&&(i=m.agent,o=m.cwd||o,c=m.title??c,u=m.createdAt,d=m.lastActivityAt,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,source:p,managed:r?.managed??h?.managed}}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(Lc(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(Lc(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(ce(e)),this.updateGauges(),this.touchSession(e.sessionId),!0}buildPushBody(e){let n=e.replace(/\s+/g," ").trim();return n?n.length<=Pc?n:`${n.slice(0,Math.max(1,Pc-3)).trimEnd()}...`:$g}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(ce(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++;b.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 rn(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);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);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);break;case"sessions.list":await this.listSessions(e,n.id,n.agent,n.cwd,n.search,n.limit,n.cursor);break}}removeClient(e){for(let n of this.sessions.values())n.clients.delete(e)}shutdown(){this.stopIdleSweep();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(){Qn({limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()}).catch(()=>{})}getDriverCounts(){let e={};for(let n of this.sessions.values())n.active&&(e[n.agent]=(e[n.agent]??0)+1);return e}async createSession(e,n,r,s,i,o){s=sr(s),_.info({agent:r,cwd:s,approvalMode:i,continueSession:o},"creating session");try{if(!(await(0,Nc.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 l=(await this.listRecentSessionsForContinue(r,s)).find(c=>!this.isDeletedSession(c.sessionId));if(l)return _.info({sessionId:l.sessionId,cwd:s},"continue mode: resuming last session"),this.resumeSession(e,n,l.sessionId,r,s,i);_.info("continue mode: no previous sessions found, creating new")}catch(a){_.warn({error:String(a)},"continue mode: error finding sessions, creating new")}try{let a=this.createDriver(r),l=this.configureDriverBeforeStart(r,a);if(r==="codex"){let p=`pending_${Date.now()}`;_.info({sessionId:p,agent:r,cwd:s},"session created (pending codex startup)"),b.increment("session.create",{agent:r}),w.emit("session.create",{sessionId:p,agent:r,cwd:s,approvalMode:i});let h={sessionId:p,agent:r,cwd:s,approvalMode:i,driver:a,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!0,bufferedPrompts:[],startupToken:1,managed:!0,claudeHookSecret:l,pendingClaudeHookApprovals:new Map};this.sessions.set(p,h),this.registerClaudeHookSession(h),this.store.upsert(ce(h)),this.updateGauges(),nr(),Zn(),this.bindDriverLifecycle(h,r,"",e),this.reply(e,n,!0,{sessionId:p}),this.startPendingCodexSession(h,e);return}let c=b.startTimer("driver.spawn"),u=await a.start(s,void 0,i),d=c();_.info({sessionId:u,agent:r,spawnMs:d},"session created"),b.increment("session.create",{agent:r}),w.emit("session.create",{sessionId:u,agent:r,cwd:s,approvalMode:i});let f={sessionId:u,agent:r,cwd:s,approvalMode:i,driver:a,clients:new Set([e]),title:"New session",createdAt:new Date().toISOString(),lastActivityAt:new Date().toISOString(),active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:!0,claudeHookSecret:l,pendingClaudeHookApprovals:new Map};this.sessions.set(u,f),this.registerClaudeHookSession(f),this.store.upsert(ce(f)),this.updateGauges(),nr(),Zn(),this.bindDriverLifecycle(f,r,"",e),this.reply(e,n,!0,{sessionId:u})}catch(a){_.error({agent:r,cwd:s,error:String(a)},"createSession error"),this.reply(e,n,!1,void 0,String(a))}}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);let f=await sn(r,s,a.cwd),p=this.currentPartialReplyText(a);if(f.length>0||p||a.approvalMode||a.pendingApproval){let h={type:"session.history",sessionId:r,messages:f,isResponding:a.isResponding||void 0,partialReplyText:p,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=b.startTimer("driver.spawn"),p=this.createDriver(s),h=this.configureDriverBeforeStart(s,p),g=await p.start(c,r,u),m=f();_.info({sessionId:g,agent:s,spawnMs:m},"session resumed"),b.increment("session.resume",{agent:s}),w.emit("session.resume",{sessionId:g,agent:s,cwd:c});let S={sessionId:g,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??[],syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:l?.managed,pendingApproval:l?.pendingApproval,claudeHookSecret:h,pendingClaudeHookApprovals:new Map};this.sessions.set(g,S),this.registerClaudeHookSession(S),this.store.upsert(ce(S)),this.updateGauges(),this.bindDriverLifecycle(S,s," (resumed)",e),this.restoreDriverPendingApproval(p,S.pendingApproval);let U=await sn(r,s,c);if(U.length>0||S.pendingApproval){_.info({sessionId:r,historyCount:U.length},"sending history messages");let se={type:"session.history",sessionId:g,messages:U,approvalMode:u,pendingApproval:S.pendingApproval};e.readyState===1&&e.send(JSON.stringify(se))}this.reply(e,n,!0,{sessionId:g})}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>ar&&e.acceptedClientMessageIds.splice(0,e.acceptedClientMessageIds.length-ar))}async sendMessage(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.driver){let l=await this.resolveReconnectSession(r,i,a);if(!l){_.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:l.agent,source:l.source},"auto-reconnecting session"),b.increment("session.reconnect",{agent:l.agent,source:l.source}),w.emit("session.reconnect",{sessionId:r,agent:l.agent,source:l.source});try{let c=this.createDriver(l.agent),u=this.configureDriverBeforeStart(l.agent,c,a?.claudeHookSecret);await c.start(l.cwd,r,l.approvalMode),this.restoreDriverPendingApproval(c,l.pendingApproval),a?(a.approvalMode=l.approvalMode,a.pendingApproval=l.pendingApproval,a.driver=c,a.active=!0,a.clients.add(e),a.lastActivityAt=l.lastActivityAt,a.lastActivityTs=Date.now(),a.isResponding=!1,a.currentReplyText="",a.acceptedClientMessageIds=or(a.acceptedClientMessageIds,l.acceptedClientMessageIds),a.syntheticApprovalRetries=a.syntheticApprovalRetries??{},a.startupInProgress=!1,a.bufferedPrompts=a.bufferedPrompts??[],a.startupToken=a.startupToken??0,a.claudeHookSecret=u??a.claudeHookSecret,a.pendingClaudeHookApprovals=a.pendingClaudeHookApprovals??new Map):(a={sessionId:r,agent:l.agent,cwd:l.cwd,approvalMode:l.approvalMode,driver:c,clients:new Set([e]),title:l.title,createdAt:l.createdAt,lastActivityAt:l.lastActivityAt,active:!0,lastActivityTs:Date.now(),isResponding:!1,currentReplyText:"",acceptedClientMessageIds:l.acceptedClientMessageIds,syntheticApprovalRetries:{},startupInProgress:!1,bufferedPrompts:[],startupToken:0,managed:l.managed,pendingApproval:l.pendingApproval,claudeHookSecret:u,pendingClaudeHookApprovals:new Map},this.sessions.set(r,a)),this.registerClaudeHookSession(a),this.bindDriverLifecycle(a,l.agent," (reconnected)"),this.store.upsert(ce(a)),this.updateGauges()}catch(c){this.reply(e,n,!1,void 0,`Failed to reconnect: ${c}`);return}}if(a.clients.add(e),a.pendingApproval){this.reply(e,n,!1,void 0,"Resolve the pending approval before sending another message.");return}if(o&&this.hasAcceptedClientMessage(a,o)){this.reply(e,n,!0,{sessionId:r,clientMessageId:o,duplicate:!0});return}if(_.info({sessionId:r,clients:a.clients.size,hasDriver:!!a.driver,active:a.active},"sending message"),w.emit("session.send",{sessionId:r,agent:a.agent,messagePreview:s.slice(0,100)}),pt(a.title)){let l=Os(s,50);l&&l!==a.title&&(a.title=l),this.store.upsert(ce(a))}if(o&&this.rememberAcceptedClientMessage(a,o),this.touchSession(a.sessionId),a.isResponding=!0,a.currentReplyText="",a.lastUserMessage=s,a.startupInProgress){a.bufferedPrompts.push(s),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0);return}a.driver.sendPrompt(s),this.reply(e,n,!0,o?{sessionId:r,clientMessageId:o}:void 0)}async sendReconnectSnapshot(e,n,r,s,i,o,a){try{let l=this.getDeletedSessionIds(),c;try{c=await Qn({agent:r,cwd:s,search:i,limit:50,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:l})}catch(f){_.warn({error:String(f)},"failed to build reconnect snapshot session list"),c={sessions:[],nextCursor:void 0}}let u;if(o&&!l.has(o)){let f=a??c.sessions.find(g=>g.sessionId===o)?.agent,p=this.sessions.get(o),h=await this.resolveReconnectSession(o,f,p);if(h){let g=await sn(o,h.agent,p?.cwd??h.cwd);u={sessionId:o,agent:h.agent,messages:g,isResponding:p?.isResponding||void 0,partialReplyText:this.currentPartialReplyText(p),approvalMode:p?.approvalMode??h.approvalMode,...p?.pendingApproval?{pendingApproval:p.pendingApproval}:{}}}}let d=this.collectReconnectPendingApprovals();b.increment("reconnect.snapshot",{activeSession:u?"true":"false"}),this.reply(e,n,!0,{snapshot:{sessions:c.sessions,nextCursor:c.nextCursor,...u?{activeSession:u}:{},...d.length>0?{pendingApprovals:d}:{}}})}catch(l){this.reply(e,n,!1,void 0,`Failed to build reconnect snapshot: ${String(l)}`)}}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,w.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),l.resolve(Mc(i)),o.isResponding=!0,this.reply(e,n,!0);return}let c=o?.syntheticApprovalRetries[s];if(o&&c&&Yn(s)){delete o.syntheticApprovalRetries[s],o.pendingApproval=void 0,w.emit("approval.response",{sessionId:r,requestId:s,approved:i}),this.touchSession(o.sessionId),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(w.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.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(ce(e)),this.updateGauges(),this.touchSession(e.sessionId),_.info({sessionId:e.sessionId,toolName:n.toolName,retryApprovalMode:r},"retrying Claude turn after synthetic approval"),s.sendPrompt(n.message)}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),_.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?(a.approvalMode=s,this.store.upsert(a),_.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}let o=i.approvalMode;i.approvalMode=s,this.store.upsert(ce(i)),_.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?.driver){this.reply(e,n,!1,void 0,"Session not found or inactive");return}w.emit("session.interrupt",{sessionId:r,agent:s.agent}),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"),w.emit("session.stop",{sessionId:r,agent:s.agent}),this.resolvePendingClaudeHookApprovals(s),s.driver?.stop(),s.active=!1,s.driver=null,s.pendingApproval=void 0,s.startupInProgress=!1,s.bufferedPrompts=[],s.startupToken+=1,this.updateGauges(),this.touchSession(s.sessionId),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)),w.emit("session.delete",{sessionId:r}),this.store.remove(r),this.updateGauges(),nr(),Zn(),this.reply(e,n,!0)}async sendHistory(e,n,r,s){let i=this.sessions.get(r);if(!i&&this.isDeletedSession(r)){this.reply(e,n,!1,void 0,"Session not found");return}i&&i.clients.add(e);let o=i?.cwd??this.store.find(r)?.cwd??"",a=this.store.find(r),l=await sn(r,s,o);_.info({sessionId:r,historyCount:l.length,isResponding:i?.isResponding,approvalMode:i?.approvalMode},"sending history");let c={type:"session.history",sessionId:r,messages:l,isResponding:i?.isResponding||void 0,partialReplyText:this.currentPartialReplyText(i),approvalMode:i?.approvalMode??a?.approvalMode,pendingApproval:i?.pendingApproval??a?.pendingApproval};e.readyState===1&&e.send(JSON.stringify(c)),this.reply(e,n,!0)}async listSessions(e,n,r,s,i,o=50,a){try{let l=await Qn({agent:r,cwd:s,search:i,limit:o,cursor:a,activeSessions:this.activeSessionSnapshots(),sessionRecords:this.store.getAll(),deletedSessionIds:this.getDeletedSessionIds()});this.reply(e,n,!0,l)}catch(l){this.reply(e,n,!1,void 0,String(l))}}createDriver(e){switch(e){case"claude":return new en;case"codex":return new Jn;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=r.clients.size,o=0,a=0;for(let l of r.clients)l.readyState===1?(l.send(s),o++):a++;if(a>0&&b.increment("broadcast.fail"),n.type!=="text.delta"&&_.debug({sessionId:e,msgType:n.type,sent:o,total:i},"broadcast"),n.type==="text.delta"){r.currentReplyText+=n.content;return}if(n.type==="session.done"){let l=r.title||e,c=this.buildPushBody(r.currentReplyText);r.currentReplyText="",this.pushSender(l,c,{sessionId:e,agent:r.agent});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 Zs(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 Oc=require("child_process");function Yg(t,e){return(0,Oc.execFileSync)(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}function Jg(t){let e=t.split(`
98
+ `).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function Bc(t,e=Yg){let n;try{n=Jg(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 vt=require("fs"),Qs=require("os"),Hc=require("crypto"),Fc=require("path");function Uc(t){return(0,Hc.randomBytes)(t).toString("base64url")}function Kg(){return`d_${Uc(12)}`}function Xg(){return(0,Qs.hostname)()}function Zg(){let t=(0,Qs.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function Qg(t){return{daemonId:Kg(),daemonSecret:Uc(32),displayName:Xg(),canonicalHost:Zg(),port:t,createdAt:new Date().toISOString()}}function Dc(t,e){(0,vt.mkdirSync)((0,Fc.dirname)(e),{recursive:!0}),(0,vt.writeFileSync)(e,JSON.stringify(t,null,2)+`
99
+ `,"utf8")}function qc(t,e=Il){try{let r=(0,vt.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,Dc(i,e)),i}}catch{}let n=Qg(t);return Dc(n,e),n}var _t=require("crypto"),wt=require("fs"),jc=require("path");function ei(t){return(0,_t.randomBytes)(t).toString("base64url")}function ti(t){return(0,_t.createHash)("sha256").update(t).digest("hex")}function Wc(t,e){let n=Buffer.from(t),r=Buffer.from(e);return n.length!==r.length?!1:(0,_t.timingSafeEqual)(n,r)}function em(t){try{let e=(0,wt.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 ln(t,e){(0,wt.mkdirSync)((0,jc.dirname)(t),{recursive:!0}),(0,wt.writeFileSync)(t,JSON.stringify(e,null,2)+`
100
+ `,"utf8")}var cr=class{constructor(e=Al){this.pairingsPath=e;this.records=em(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4){let n=`pair_${ei(8)}`,r=ei(24),s=new Date(Date.now()+e).toISOString(),i={pairingId:n,pairNonce:r,expiresAt:s};return this.windows.set(r,i),i}consumeWindow(e){let n=this.windows.get(e);return!n||(this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let r=new Date().toISOString(),s=ei(32),i={deviceId:e,deviceName:n,tokenHash:ti(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),ln(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=ti(n);return Wc(s.tokenHash,i)?(r&&(s.lastSeenAt=new Date().toISOString(),ln(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let r=ti(e),s=this.records.find(i=>!i.revokedAt&&Wc(i.tokenHash,r));return s?(n&&(s.lastSeenAt=new Date().toISOString(),ln(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(),ln(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),ln(this.pairingsPath,this.records)}};function bt(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}function tm(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Gc(t,e){return tm(t)??e}function ni(t,e){return!!(t&&e&&t===e)}function $c(t,e,n,r=!0){return t?ni(t,e)?!0:!!n(t,r):!1}var Vc=require("child_process");function ri(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Yc(t){if(!ri(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function nm(t){if(!ri(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function rm(t){if(!ri(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function si(t){return!!t&&!nm(t)&&!rm(t)}function It(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Jc(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function sm(t){let e=[],n=[];for(let r of Object.values(t))if(r)for(let s of r)s.internal||s.family!=="IPv4"||si(s.address)&&(Yc(s.address)?e.push(s.address):n.push(s.address));return[...e,...n]}function zc(t){let e=JSON.parse(t),n=It(e.Self?.DNSName),r=(e.Self?.TailscaleIPs??[]).map(o=>It(o)).filter(o=>!!o).filter(o=>Yc(o)&&si(o)),s=r[0]??n,i=[...n&&n!==s?[n]:[],...r.filter(o=>o!==s)];return{canonicalHost:s,fallbackHosts:i}}function Kc(t=Vc.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 zc(r)}catch{}try{let n=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return zc(n)}catch{return{fallbackHosts:[]}}}function Xc(t){let e=It(t.canonicalHost),n=It(t.configuredCanonicalHost)||It(t.tailscaleCanonicalHost)||e||"localhost",r=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...sm(t.interfaces)].map(s=>It(s)).filter(s=>!!s).filter(s=>si(s)).filter((s,i,o)=>s!==n&&o.indexOf(s)===i);return{canonicalHost:n,fallbackHosts:r}}function Zc(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 j=L.child({module:"daemon"}),cn=L.child({module:"ws"}),ue=new lr,F=qc(v.port),Re=new cr,ur=new Set,Pe=new WeakMap,Qc=!1,ru=Date.now(),At=null;function kt(){let t=Kc();return Xc({canonicalHost:F.canonicalHost,configuredCanonicalHost:v.canonicalHost,configuredFallbackHosts:Jc(v.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,tu.networkInterfaces)()})}async function ii(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 D(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n,null,2))}function su(){let t=Re.openWindow(),e=kt(),n=e.canonicalHost,r=F.port,s=e.fallbackHosts.length>0?e.fallbackHosts:void 0;if(v.relayUrl)try{let i=new URL(v.relayUrl);n=i.hostname,r=i.port?Number(i.port):i.protocol==="https:"?443:80,s=[e.canonicalHost,...s??[]].filter(Boolean)}catch{j.warn({relayUrl:v.relayUrl},"invalid VIBELET_RELAY_URL, ignoring")}return{type:"vibelet-pair",daemonId:F.daemonId,displayName:F.displayName,canonicalHost:n,fallbackHosts:s,port:r,pairNonce:t.pairNonce,expiresAt:t.expiresAt}}async function im(t){let e=await(0,Ge.readdir)(t),n=[];for(let r of e){if(r.startsWith("."))continue;let s=await(0,Ge.stat)((0,dr.join)(t,r)).catch(()=>null);s&&n.push({name:r,isDirectory:s.isDirectory()})}return n.sort((r,s)=>r.isDirectory!==s.isDirectory?r.isDirectory?-1:1:r.name.localeCompare(s.name)),{entries:n}}var un=(0,eu.createServer)(async(t,e)=>{let n=new URL(t.url??"/",`http://localhost:${v.port}`);if(n.pathname==="/health"){let s=kt(),i={status:"ok",version:ft,daemonId:F.daemonId,displayName:F.displayName,canonicalHost:s.canonicalHost,uptimeSeconds:Math.round((Date.now()-ru)/1e3),activeSessions:ue.getActiveSessionCount(),pairedDevices:Re.pairedCount(),wsClients:re.clients.size,drivers:ue.getDriverCounts(),metrics:b.snapshot()};v.relayUrl&&(i.relayUrl=v.relayUrl),D(e,200,i);return}if(t.method==="POST"&&n.pathname==="/pair/open"){if(!bt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}D(e,200,su());return}if(t.method==="POST"&&n.pathname==="/pair/reset"){if(!bt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}Re.reset(),D(e,200,{ok:!0});return}if(t.method==="POST"&&n.pathname==="/shutdown"){if(!bt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}D(e,200,{status:"stopping"}),setTimeout(()=>$e("HTTP /shutdown request"),50);return}if(t.method==="POST"&&n.pathname==="/hook/claude/session-start"){if(!bt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}try{let s=await ii(t),i=t.headers[Zt],o=Array.isArray(i)?i[0]:i;ue.handleClaudeSessionStartHook(o,s),D(e,200,{ok:!0})}catch(s){D(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/hook/claude/permission-request"){if(!bt(t.socket.remoteAddress)){D(e,403,{error:"forbidden"});return}try{let s=await ii(t),i=t.headers[Zt],o=Array.isArray(i)?i[0]:i,a=await ue.handleClaudePermissionHook(o,s);D(e,200,a)}catch(s){D(e,400,{error:String(s)})}return}if(t.method==="POST"&&n.pathname==="/pair/create"){try{let s=await ii(t);if(s.daemonId!==F.daemonId||typeof s.pairNonce!="string"||typeof s.deviceId!="string"||typeof s.deviceName!="string"){D(e,400,{error:"invalid_pair_request"});return}if(!Re.consumeWindow(s.pairNonce)){D(e,401,{error:"pair_window_expired"});return}let o=Re.issuePairToken(s.deviceId,s.deviceName),a=kt();D(e,200,{daemonId:F.daemonId,displayName:F.displayName,canonicalHost:a.canonicalHost,fallbackHosts:a.fallbackHosts,port:F.port,deviceId:s.deviceId,pairToken:o})}catch(s){D(e,400,{error:String(s)})}return}let r=Gc(t.headers.authorization,n.searchParams.get("token"));if(!$c(r,v.legacyToken,(s,i)=>Re.validateAnyPairToken(s,i),!1)){e.writeHead(401),e.end("Unauthorized");return}if(n.pathname==="/file"){let s=n.searchParams.get("path");if(!s){e.writeHead(400),e.end("Missing path parameter");return}try{let i=sr(s);if(!(await(0,Ge.stat)(i)).isFile()){e.writeHead(404),e.end("Not a file");return}let a=(0,dr.extname)(i).toLowerCase(),c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".pdf":"application/pdf"}[a]||"application/octet-stream",u=await(0,Ge.readFile)(i);e.writeHead(200,{"Content-Type":c,"Content-Length":u.length}),e.end(u)}catch{e.writeHead(404),e.end("File not found")}return}e.writeHead(200),e.end(`Vibelet Daemon v${ft}`)}),re=new Nr.default({server:un});un.on("connection",t=>{ur.add(t),t.on("close",()=>{ur.delete(t)})});re.on("connection",(t,e)=>{let r=new URL(e.url??"/",`http://localhost:${v.port}`).searchParams.get("token");if(r&&ni(r,v.legacyToken))Pe.set(t,{authMode:"query_token"}),b.increment("ws.auth.success",{mode:"query_token"}),ue.prewarmCaches();else if(r){let s=Re.validateAnyPairToken(r);if(s)Pe.set(t,{authMode:"query_token",deviceId:s.deviceId}),b.increment("ws.auth.success",{mode:"query_token"}),ue.prewarmCaches();else{b.increment("ws.auth.failure",{mode:"query_token"}),t.close(4001,"Unauthorized");return}}cn.info({clients:re.clients.size},"client connected"),b.increment("ws.connect"),b.gauge("ws.clients",re.clients.size),w.emit("ws.connect",{clients:re.clients.size,authMode:Pe.get(t)?.authMode??"pending",deviceId:Pe.get(t)?.deviceId}),t.on("message",async s=>{try{let i=JSON.parse(Zc(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(!Pe.has(t)){if(o.action==="auth.hello"&&o.daemonId===F.daemonId&&Re.validatePairToken(o.deviceId,o.pairToken)){Pe.set(t,{authMode:"auth_hello",deviceId:o.deviceId}),b.increment("ws.auth.success",{mode:"auth_hello"}),ue.prewarmCaches(),t.send(JSON.stringify({type:"response",id:o.id,ok:!0,data:{daemonId:F.daemonId,displayName:F.displayName}}));return}if(o.action==="auth.hello"){b.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}b.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)w.emitApp(a.event,a.level,a.data??{},a.ts),(a.level==="error"?j.error:a.level==="warn"?j.warn:j.info).call(j,{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 im(o.path);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=Pe.get(t);Zs(i,{deviceId:a?.deviceId,registerToken:Js,unregisterToken:Ks,respond:l=>t.send(JSON.stringify(l))});return}if(i.action==="push.unregister"){let a=Pe.get(t);Zs(i,{deviceId:a?.deviceId,registerToken:Js,unregisterToken:Ks,respond:l=>t.send(JSON.stringify(l))});return}await ue.handle(t,o)}catch(i){cn.error({error:String(i)},"message handling error"),t.send(JSON.stringify({type:"error",sessionId:"",message:String(i)}))}}),t.on("close",s=>{cn.info({clients:re.clients.size,code:s},"client disconnected"),b.increment("ws.disconnect"),b.increment("ws.disconnect.code",{code:String(s)}),b.gauge("ws.clients",re.clients.size),w.emit("ws.disconnect",{clients:re.clients.size,code:s}),ue.removeClient(t)}),t.on("error",s=>{cn.error({error:s.message},"websocket error")})});function oi(){for(let t of ur)try{t.destroy()}catch{}ur.clear()}function iu(){let t=Dl({auditPath:ct,stdoutLogPath:Un,stderrLogPath:qn,auditMaxBytes:v.auditMaxBytes,logMaxBytes:v.daemonLogMaxBytes});t.trimmedFiles>0&&j.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 om(){At||(At=setInterval(iu,v.storageHousekeepingIntervalMs),At.unref())}function am(){At&&(clearInterval(At),At=null)}function $e(t,e=0){if(!Qc){Qc=!0,j.info({reason:t,exitCode:e},"shutting down"),w.emit("daemon.shutdown",{reason:t,exitCode:e,uptimeSeconds:Math.round((Date.now()-ru)/1e3)}),b.stopPeriodicLog(),am(),ue.shutdown();for(let n of re.clients)try{n.close(1001,"Server shutting down"),n.terminate()}catch{}re.close(n=>{n&&j.error({error:String(n)},"websocket close error")}),un.close(n=>{if(n){j.error({error:String(n)},"http close error"),oi(),process.exit(1);return}oi(),process.exit(e)}),setTimeout(()=>{j.error("force exiting after shutdown timeout"),oi(),process.exit(e||1)},3e3).unref()}}re.on("error",t=>{cn.error({error:t.message},"wss error")});un.on("error",t=>{if(t.code==="EADDRINUSE"){let e=Bc(v.port).filter(n=>n.pid!==process.pid);j.error({port:v.port,occupants:e},"port is already in use. Stop the existing process or use VIBE_PORT=<port> to specify another port")}else j.error({error:String(t)},"server error");$e(`httpServer error: ${t.code??t.message}`,1)});process.once("SIGINT",()=>$e("SIGINT"));process.once("SIGTERM",()=>$e("SIGTERM"));process.once("SIGHUP",()=>$e("SIGHUP"));process.once("SIGTTIN",()=>$e("SIGTTIN"));process.once("SIGTSTP",()=>$e("SIGTSTP"));process.on("uncaughtException",t=>{j.error({error:String(t),stack:t.stack},"uncaughtException"),w.emit("daemon.error",{type:"uncaughtException",error:String(t)})});process.on("unhandledRejection",t=>{j.error({reason:String(t)},"unhandledRejection"),w.emit("daemon.error",{type:"unhandledRejection",reason:String(t)})});un.listen(v.port,async()=>{iu(),w.emit("daemon.start",{port:v.port}),b.startPeriodicLog(),om(),j.info({port:v.port,daemonId:F.daemonId,displayName:F.displayName,canonicalHost:kt().canonicalHost,fallbackHosts:kt().fallbackHosts,claudePath:v.claudePath,codexPath:v.codexPath,auditMaxBytes:v.auditMaxBytes,daemonLogMaxBytes:v.daemonLogMaxBytes,storageHousekeepingIntervalMs:v.storageHousekeepingIntervalMs,turnStallTimeoutMs:v.turnStallTimeoutMs},"daemon started");let t=kt(),e=su();Vt(`
101
101
  \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
102
102
  \u2551 Vibelet Daemon v${ft} \u2551
103
103
  \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
104
- \u2551 Port: ${String(_.port).padEnd(28)}\u2551
104
+ \u2551 Port: ${String(v.port).padEnd(28)}\u2551
105
105
  \u2551 ID: ${F.daemonId.slice(0,28).padEnd(28)}\u2551
106
106
  \u2551 Host: ${t.canonicalHost.slice(0,28).padEnd(28)}\u2551
107
107
  \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
@@ -110,10 +110,10 @@ Pair with: npx @vibelet/cli or npx vibelet
110
110
  Host: ${t.canonicalHost}
111
111
  Fallbacks: ${t.fallbackHosts.join(", ")||"(none)"}
112
112
 
113
- Claude: ${_.claudePath}
114
- Codex: ${_.codexPath}
115
- `);try{let r=await tu.default.toString(JSON.stringify(e),{type:"terminal",small:!0});Vt(`
113
+ Claude: ${v.claudePath}
114
+ Codex: ${v.codexPath}
115
+ `);try{let n=await nu.default.toString(JSON.stringify(e),{type:"terminal",small:!0});Vt(`
116
116
  Scan this QR code with Vibelet app:
117
117
 
118
- ${r}
118
+ ${n}
119
119
  `)}catch{}});