@beachviber/agent 1.10.7 → 1.10.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +45 -44
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,76 +1,77 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);
|
|
3
|
-
var
|
|
3
|
+
var Uu=Object.create;var Cr=Object.defineProperty;var Fu=Object.getOwnPropertyDescriptor;var ju=Object.getOwnPropertyNames;var qu=Object.getPrototypeOf,Ku=Object.prototype.hasOwnProperty;var C=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Wu=(t,e)=>{for(var n in e)Cr(t,n,{get:e[n],enumerable:!0})},Hu=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ju(e))!Ku.call(t,s)&&s!==n&&Cr(t,s,{get:()=>e[s],enumerable:!(r=Fu(e,s))||r.enumerable});return t};var lt=(t,e,n)=>(n=t!=null?Uu(qu(t)):{},Hu(e||!t||!t.__esModule?Cr(n,"default",{value:t,enumerable:!0}):n,t));function Yu(){let t=new Map;for(let[e,n]of Object.entries(N)){for(let[r,s]of Object.entries(n))N[r]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[r]=N[r],t.set(s[0],s[1]);Object.defineProperty(N,e,{value:n,enumerable:!1})}return Object.defineProperty(N,"codes",{value:t,enumerable:!1}),N.color.close="\x1B[39m",N.bgColor.close="\x1B[49m",N.color.ansi=Ni(),N.color.ansi256=Li(),N.color.ansi16m=Bi(),N.bgColor.ansi=Ni(10),N.bgColor.ansi256=Li(10),N.bgColor.ansi16m=Bi(10),Object.defineProperties(N,{rgbToAnsi256:{value(e,n,r){return e===n&&n===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(e){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(i=>i+i).join(""));let s=Number.parseInt(r,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:e=>N.rgbToAnsi256(...N.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let n,r,s;if(e>=232)n=((e-232)*10+8)/255,r=n,s=n;else{e-=16;let a=e%36;n=Math.floor(e/36)/5,r=Math.floor(a/6)/5,s=a%6/5}let i=Math.max(n,r,s)*2;if(i===0)return 30;let o=30+(Math.round(s)<<2|Math.round(r)<<1|Math.round(n));return i===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(e,n,r)=>N.ansi256ToAnsi(N.rgbToAnsi256(e,n,r)),enumerable:!1},hexToAnsi:{value:e=>N.ansi256ToAnsi(N.hexToAnsi256(e)),enumerable:!1}}),N}var Ni,Li,Bi,N,ky,Vu,Gu,vy,zu,ie,Mi=j(()=>{Ni=(t=0)=>e=>`\x1B[${e+t}m`,Li=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,Bi=(t=0)=>(e,n,r)=>`\x1B[${38+t};2;${e};${n};${r}m`,N={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},ky=Object.keys(N.modifier),Vu=Object.keys(N.color),Gu=Object.keys(N.bgColor),vy=[...Vu,...Gu];zu=Yu(),ie=zu});import Ir from"node:process";import Ju from"node:os";import Di from"node:tty";function Z(t,e=globalThis.Deno?globalThis.Deno.args:Ir.argv){let n=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(n+t),s=e.indexOf("--");return r!==-1&&(s===-1||r<s)}function Qu(){if("FORCE_COLOR"in L)return L.FORCE_COLOR==="true"?1:L.FORCE_COLOR==="false"?0:L.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(L.FORCE_COLOR,10),3)}function Zu(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Xu(t,{streamIsTTY:e,sniffFlags:n=!0}={}){let r=Qu();r!==void 0&&(Sn=r);let s=n?Sn:r;if(s===0)return 0;if(n){if(Z("color=16m")||Z("color=full")||Z("color=truecolor"))return 3;if(Z("color=256"))return 2}if("TF_BUILD"in L&&"AGENT_NAME"in L)return 1;if(t&&!e&&s===void 0)return 0;let i=s||0;if(L.TERM==="dumb")return i;if(Ir.platform==="win32"){let o=Ju.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in L)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in L)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in L)||L.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in L)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(L.TEAMCITY_VERSION)?1:0;if(L.COLORTERM==="truecolor"||L.TERM==="xterm-kitty"||L.TERM==="xterm-ghostty"||L.TERM==="wezterm")return 3;if("TERM_PROGRAM"in L){let o=Number.parseInt((L.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(L.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(L.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(L.TERM)||"COLORTERM"in L?1:i}function $i(t,e={}){let n=Xu(t,{streamIsTTY:t&&t.isTTY,...e});return Zu(n)}var L,Sn,ed,Ui,Fi=j(()=>{({env:L}=Ir);Z("no-color")||Z("no-colors")||Z("color=false")||Z("color=never")?Sn=0:(Z("color")||Z("colors")||Z("color=true")||Z("color=always"))&&(Sn=1);ed={stdout:$i({isTTY:Di.isatty(1)}),stderr:$i({isTTY:Di.isatty(2)})},Ui=ed});function ji(t,e,n){let r=t.indexOf(e);if(r===-1)return t;let s=e.length,i=0,o="";do o+=t.slice(i,r)+e+n,i=r+s,r=t.indexOf(e,i);while(r!==-1);return o+=t.slice(i),o}function qi(t,e,n,r){let s=0,i="";do{let o=t[r-1]==="\r";i+=t.slice(s,o?r-1:r)+e+(o?`\r
|
|
4
4
|
`:`
|
|
5
5
|
`)+n,s=r+1,r=t.indexOf(`
|
|
6
|
-
`,s)}while(r!==-1);return i+=t.slice(s),i}var
|
|
7
|
-
`);return i!==-1&&(e=$i(e,s,r,i)),r+e+s};Object.defineProperties(Ft.prototype,lt);Ju=Ft(),py=Ft({level:ji?ji.level:0}),m=Ju});var En,Ki=K(()=>{"use strict";En=class{state="disconnected";context={consecutiveFailures:0,reconnectDelay:1e3,disconnectReason:"none",wasSleeping:!1};transition(e){let n=this.state,r=this._nextState(n,e);if(r===void 0)throw new Error(`Invalid transition: ${e.type} from state "${n}"`);return this.state=r,r}reset(){this.state="disconnected",this.context={consecutiveFailures:0,reconnectDelay:1e3,disconnectReason:"none",wasSleeping:!1}}get connectionPhase(){switch(this.state){case"disconnected":case"connecting":case"registering":return"registering";case"pairing":case"setup_reconnecting":case"setup_pairing":return"pairing";case"paired":return"paired";case"paired_sleeping":return"paired_sleeping";case"reconnecting":return"paired"}}get inSetupMode(){return this.state==="setup_reconnecting"||this.state==="setup_pairing"}get disconnectedByRemote(){return this.context.disconnectReason==="remote"}_nextState(e,n){switch(e){case"disconnected":return this._fromDisconnected(n);case"connecting":return this._fromConnecting(n);case"registering":return this._fromRegistering(n);case"pairing":return this._fromPairing(n);case"paired":return this._fromPaired(n);case"paired_sleeping":return this._fromPairedSleeping(n);case"reconnecting":return this._fromReconnecting(n);case"setup_reconnecting":return this._fromSetupReconnecting(n);case"setup_pairing":return this._fromSetupPairing(n)}}_fromDisconnected(e){switch(e.type){case"CONNECT":return this.context.disconnectReason="none","connecting";case"ENTER_SETUP":return this.context.disconnectReason="none",e.hasSavedState?"setup_reconnecting":"setup_pairing";case"FORCE_DISCONNECT":return"disconnected"}}_fromConnecting(e){switch(e.type){case"WS_OPEN":return this.context.consecutiveFailures=0,this.context.reconnectDelay=1e3,"registering";case"WS_CLOSE":return"reconnecting"}}_fromRegistering(e){switch(e.type){case"REGISTERED":return e.hasSharedSecret&&this.context.wasSleeping?(this.context.wasSleeping=!1,"paired_sleeping"):e.hasSharedSecret?"paired":"pairing";case"WS_CLOSE":return"reconnecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected"}}_fromPairing(e){switch(e.type){case"PAIRED":return"paired";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected";case"WS_CLOSE":return this.context.disconnectReason="network","disconnected"}}_fromPaired(e){switch(e.type){case"WS_CLOSE":return"reconnecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected";case"SLEEP":return"paired_sleeping"}}_fromPairedSleeping(e){switch(e.type){case"WAKE":return"paired";case"WS_CLOSE":return this.context.wasSleeping=!0,"reconnecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote",this.context.wasSleeping=!1,"disconnected";case"SLEEP":return"paired_sleeping"}}_fromReconnecting(e){switch(e.type){case"RECONNECT_TIMER":return"connecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected"}}_fromSetupReconnecting(e){switch(e.type){case"PAIRED":return"paired";case"SETUP_RECONNECT_FAILED":return"setup_pairing";case"CONNECT":return"setup_reconnecting";case"WS_OPEN":return"setup_reconnecting";case"WS_CLOSE":return"setup_reconnecting";case"REGISTERED":return e.hasSharedSecret&&this.context.wasSleeping?(this.context.wasSleeping=!1,"paired_sleeping"):e.hasSharedSecret?"paired":"setup_pairing"}}_fromSetupPairing(e){switch(e.type){case"PAIRED":return"paired";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected";case"CONNECT":return"setup_pairing";case"WS_OPEN":return"setup_pairing";case"WS_CLOSE":return"setup_pairing";case"REGISTERED":return"setup_pairing"}}}});function Wi(t){Rr=t}function Vi(){d.machine.reset(),d.ws=null,d.heartbeatTimer=null,d.deviceId="",d.deviceToken="",d.ownKeyPair=null,d.peerPublicKey=null,d.sharedSecret=null,d.peerAppVersion=null,d.peerCapabilities=[],d.lastMessageAt=0,d.verifyCodeResolve=null,d.registeredResolve=null,d.shuttingDown=!1,d.wakeExpiresAt=null,d.wakeTimer=null,d.wakeLockout={failedAttempts:0,lockedUntil:null}}var z,Rr,Hi,Pr,d,ut=K(()=>{"use strict";Ki();z="1.10.7",Rr="wss://relay.beachviber.com";Hi=3e4,Pr=3e4,d={machine:new En,ws:null,heartbeatTimer:null,projects:[],deviceId:"",deviceToken:"",get connectionPhase(){return this.machine.connectionPhase},get inSetupMode(){return this.machine.inSetupMode},get disconnectedByRemote(){return this.machine.disconnectedByRemote},get consecutiveFailures(){return this.machine.context.consecutiveFailures},get reconnectDelay(){return this.machine.context.reconnectDelay},ownKeyPair:null,peerPublicKey:null,sharedSecret:null,peerAppVersion:null,peerCapabilities:[],lastMessageAt:0,verifyCodeResolve:null,registeredResolve:null,enterSetupMode:null,shuttingDown:!1,get wakeState(){return this.machine.state==="paired_sleeping"?"sleeping":"awake"},wakeExpiresAt:null,wakeTimer:null,wakeLockout:{failedAttempts:0,lockedUntil:null},onSleepTransition:null}});var _e=S((_y,zi)=>{"use strict";var Gi=["nodebuffer","arraybuffer","fragments"],Yi=typeof Blob<"u";Yi&&Gi.push("blob");zi.exports={BINARY_TYPES:Gi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Yi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var jt=S((wy,bn)=>{"use strict";var{EMPTY_BUFFER:Qu}=_e(),Ar=Buffer[Symbol.species];function Zu(t,e){if(t.length===0)return Qu;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 Ar(n.buffer,n.byteOffset,r):n}function Ji(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function Qi(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function Xu(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Or(t){if(Or.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Ar(t):ArrayBuffer.isView(t)?e=new Ar(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Or.readOnly=!1),e}bn.exports={concat:Zu,mask:Ji,toArrayBuffer:Xu,toBuffer:Or,unmask:Qi};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=C("bufferutil");bn.exports.mask=function(e,n,r,s,i){i<48?Ji(e,n,r,s,i):t.mask(e,n,r,s,i)},bn.exports.unmask=function(e,n){e.length<32?Qi(e,n):t.unmask(e,n)}}catch{}});var eo=S((Sy,Xi)=>{"use strict";var Zi=Symbol("kDone"),Nr=Symbol("kRun"),Lr=class{constructor(e){this[Zi]=()=>{this.pending--,this[Nr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Nr]()}[Nr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Zi])}}};Xi.exports=Lr});var Kt=S((Ey,so)=>{"use strict";var qt=C("zlib"),to=jt(),ed=eo(),{kStatusCode:no}=_e(),td=Buffer[Symbol.species],nd=Buffer.from([0,0,255,255]),kn=Symbol("permessage-deflate"),we=Symbol("total-length"),dt=Symbol("callback"),Ce=Symbol("buffers"),ft=Symbol("error"),Tn,Br=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,!Tn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Tn=new ed(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[dt];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){Tn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){Tn.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"?qt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=qt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[kn]=this,this._inflate[we]=0,this._inflate[Ce]=[],this._inflate.on("error",sd),this._inflate.on("data",ro)}this._inflate[dt]=r,this._inflate.write(e),n&&this._inflate.write(nd),this._inflate.flush(()=>{let i=this._inflate[ft];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=to.concat(this._inflate[Ce],this._inflate[we]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[we]=0,this._inflate[Ce]=[],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"?qt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=qt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[we]=0,this._deflate[Ce]=[],this._deflate.on("data",rd)}this._deflate[dt]=r,this._deflate.write(e),this._deflate.flush(qt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=to.concat(this._deflate[Ce],this._deflate[we]);n&&(i=new td(i.buffer,i.byteOffset,i.length-4)),this._deflate[dt]=null,this._deflate[we]=0,this._deflate[Ce]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};so.exports=Br;function rd(t){this[Ce].push(t),this[we]+=t.length}function ro(t){if(this[we]+=t.length,this[kn]._maxPayload<1||this[we]<=this[kn]._maxPayload){this[Ce].push(t);return}this[ft]=new RangeError("Max payload size exceeded"),this[ft].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ft][no]=1009,this.removeListener("data",ro),this.reset()}function sd(t){if(this[kn]._inflate=null,this[ft]){this[dt](this[ft]);return}t[no]=1007,this[dt](t)}});var pt=S((by,vn)=>{"use strict";var{isUtf8:io}=C("buffer"),{hasBlob:id}=_e(),od=[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 ad(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Mr(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 ld(t){return id&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}vn.exports={isBlob:ld,isValidStatusCode:ad,isValidUTF8:Mr,tokenChars:od};if(io)vn.exports.isValidUTF8=function(t){return t.length<24?Mr(t):io(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=C("utf-8-validate");vn.exports.isValidUTF8=function(e){return e.length<32?Mr(e):t(e)}}catch{}});var jr=S((Ty,po)=>{"use strict";var{Writable:cd}=C("stream"),oo=Kt(),{BINARY_TYPES:ud,EMPTY_BUFFER:ao,kStatusCode:dd,kWebSocket:fd}=_e(),{concat:Dr,toArrayBuffer:pd,unmask:hd}=jt(),{isValidStatusCode:gd,isValidUTF8:lo}=pt(),Cn=Buffer[Symbol.species],X=0,co=1,uo=2,fo=3,$r=4,Ur=5,In=6,Fr=class extends cd{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ud[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[fd]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=X}_write(e,n,r){if(this._opcode===8&&this._state==X)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Cn(r.buffer,r.byteOffset+e,r.length-e),new Cn(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 Cn(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case X:this.getInfo(e);break;case co:this.getPayloadLength16(e);break;case uo:this.getPayloadLength64(e);break;case fo:this.getMask();break;case $r:this.getData(e);break;case Ur:case In: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[oo.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=co:this._payloadLength===127?this._state=uo: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=fo:this._state=$r}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=$r}getData(e){let n=ao;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&&hd(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Ur,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[oo.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===X&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=X;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Dr(r,n):this._binaryType==="arraybuffer"?s=pd(Dr(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=X):(this._state=In,setImmediate(()=>{this.emit("message",s,!0),this._state=X,this.startLoop(e)}))}else{let s=Dr(r,n);if(!this._skipUTF8Validation&&!lo(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Ur||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=X):(this._state=In,setImmediate(()=>{this.emit("message",s,!1),this._state=X,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ao),this.end();else{let r=e.readUInt16BE(0);if(!gd(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new Cn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!lo(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=X;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=X):(this._state=In,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=X,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[dd]=s,o}};po.exports=Fr});var Wr=S((vy,mo)=>{"use strict";var{Duplex:ky}=C("stream"),{randomFillSync:md}=C("crypto"),ho=Kt(),{EMPTY_BUFFER:yd,kWebSocket:_d,NOOP:wd}=_e(),{isBlob:ht,isValidStatusCode:Sd}=pt(),{mask:go,toBuffer:We}=jt(),ee=Symbol("kByteLength"),Ed=Buffer.alloc(4),xn=8*1024,He,gt=xn,ie=0,bd=1,Td=2,qr=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=ie,this.onerror=wd,this[_d]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||Ed,n.generateMask?n.generateMask(r):(gt===xn&&(He===void 0&&(He=Buffer.alloc(xn)),md(He,0,xn),gt=0),r[0]=He[gt++],r[1]=He[gt++],r[2]=He[gt++],r[3]=He[gt++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[ee]!==void 0?a=n[ee]:(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?(go(e,r,c,i,a),[c]):(go(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=yd;else{if(typeof e!="number"||!Sd(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={[ee]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ie?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):ht(e)?(s=e.size,i=!1):(e=We(e),s=e.length,i=We.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ee]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ht(e)?this._state!==ie?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ie?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):ht(e)?(s=e.size,i=!1):(e=We(e),s=e.length,i=We.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ee]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ht(e)?this._state!==ie?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ie?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[ho.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):ht(e)?(a=e.size,l=!1):(e=We(e),a=e.length,l=We.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={[ee]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};ht(e)?this._state!==ie?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==ie?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[ee],this._state=Td,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[ee];let o=We(i);n?this.dispatch(o,n,r,s):(this._state=ie,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(kd,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[ho.extensionName];this._bufferedBytes+=r[ee],this._state=bd,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[ee],this._state=ie,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===ie&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ee],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ee],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)}};mo.exports=qr;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 kd(t,e,n){Kr(t,e,n),t.onerror(e)}});var vo=S((Cy,ko)=>{"use strict";var{kForOnEventAttribute:Wt,kListener:Hr}=_e(),yo=Symbol("kCode"),_o=Symbol("kData"),wo=Symbol("kError"),So=Symbol("kMessage"),Eo=Symbol("kReason"),mt=Symbol("kTarget"),bo=Symbol("kType"),To=Symbol("kWasClean"),Se=class{constructor(e){this[mt]=null,this[bo]=e}get target(){return this[mt]}get type(){return this[bo]}};Object.defineProperty(Se.prototype,"target",{enumerable:!0});Object.defineProperty(Se.prototype,"type",{enumerable:!0});var Ve=class extends Se{constructor(e,n={}){super(e),this[yo]=n.code===void 0?0:n.code,this[Eo]=n.reason===void 0?"":n.reason,this[To]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[yo]}get reason(){return this[Eo]}get wasClean(){return this[To]}};Object.defineProperty(Ve.prototype,"code",{enumerable:!0});Object.defineProperty(Ve.prototype,"reason",{enumerable:!0});Object.defineProperty(Ve.prototype,"wasClean",{enumerable:!0});var yt=class extends Se{constructor(e,n={}){super(e),this[wo]=n.error===void 0?null:n.error,this[So]=n.message===void 0?"":n.message}get error(){return this[wo]}get message(){return this[So]}};Object.defineProperty(yt.prototype,"error",{enumerable:!0});Object.defineProperty(yt.prototype,"message",{enumerable:!0});var Ht=class extends Se{constructor(e,n={}){super(e),this[_o]=n.data===void 0?null:n.data}get data(){return this[_o]}};Object.defineProperty(Ht.prototype,"data",{enumerable:!0});var vd={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Wt]&&s[Hr]===e&&!s[Wt])return;let r;if(t==="message")r=function(i,o){let a=new Ht("message",{data:o?i:i.toString()});a[mt]=this,Rn(e,this,a)};else if(t==="close")r=function(i,o){let a=new Ve("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[mt]=this,Rn(e,this,a)};else if(t==="error")r=function(i){let o=new yt("error",{error:i,message:i.message});o[mt]=this,Rn(e,this,o)};else if(t==="open")r=function(){let i=new Se("open");i[mt]=this,Rn(e,this,i)};else return;r[Wt]=!!n[Wt],r[Hr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Hr]===e&&!n[Wt]){this.removeListener(t,n);break}}};ko.exports={CloseEvent:Ve,ErrorEvent:yt,Event:Se,EventTarget:vd,MessageEvent:Ht};function Rn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Vr=S((Iy,Co)=>{"use strict";var{tokenChars:Vt}=pt();function ce(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Cd(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,a,l=-1,c=-1,u=-1,p=0;for(;p<t.length;p++)if(c=t.charCodeAt(p),o===void 0)if(u===-1&&Vt[c]===1)l===-1&&(l=p);else if(p!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let f=t.slice(l,u);c===44?(ce(e,f,n),n=Object.create(null)):o=f,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(u===-1&&Vt[c]===1)l===-1&&(l=p);else if(c===32||c===9)u===-1&&l!==-1&&(u=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p),ce(n,t.slice(l,u),!0),c===44&&(ce(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,p),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Vt[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);l===-1?l=p:r||(r=!0),s=!1}else if(i)if(Vt[c]===1)l===-1&&(l=p);else if(c===34&&l!==-1)i=!1,u=p;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&t.charCodeAt(p-1)===61)i=!0;else if(u===-1&&Vt[c]===1)l===-1&&(l=p);else if(l!==-1&&(c===32||c===9))u===-1&&(u=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let f=t.slice(l,u);r&&(f=f.replace(/\\/g,""),r=!1),ce(n,a,f),c===44&&(ce(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=p);let g=t.slice(l,u);return o===void 0?ce(e,g,n):(a===void 0?ce(n,g,!0):r?ce(n,a,g.replace(/\\/g,"")):ce(n,a,g),ce(e,o,n)),e}function Id(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(", ")}Co.exports={format:Id,parse:Cd}});var Nn=S((Py,$o)=>{"use strict";var xd=C("events"),Rd=C("https"),Pd=C("http"),Ro=C("net"),Ad=C("tls"),{randomBytes:Od,createHash:Nd}=C("crypto"),{Duplex:xy,Readable:Ry}=C("stream"),{URL:Gr}=C("url"),Ie=Kt(),Ld=jr(),Bd=Wr(),{isBlob:Md}=pt(),{BINARY_TYPES:Io,CLOSE_TIMEOUT:Dd,EMPTY_BUFFER:Pn,GUID:$d,kForOnEventAttribute:Yr,kListener:Ud,kStatusCode:Fd,kWebSocket:j,NOOP:Po}=_e(),{EventTarget:{addEventListener:jd,removeEventListener:qd}}=vo(),{format:Kd,parse:Wd}=Vr(),{toBuffer:Hd}=jt(),Ao=Symbol("kAborted"),zr=[8,13],Ee=["CONNECTING","OPEN","CLOSING","CLOSED"],Vd=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,B=class t extends xd{constructor(e,n,r){super(),this._binaryType=Io[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Pn,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]),Oo(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Io.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 Ld({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Bd(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[j]=this,i[j]=this,e[j]=this,s.on("conclude",zd),s.on("drain",Jd),s.on("error",Qd),s.on("message",Zd),s.on("ping",Xd),s.on("pong",ef),i.onerror=tf,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Bo),e.on("data",On),e.on("end",Mo),e.on("error",Do),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[Ie.extensionName]&&this._extensions[Ie.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){J(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())}),Lo(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){Jr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Pn,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){Jr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Pn,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){Jr(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Ie.extensionName]||(s.compress=!1),this._sender.send(e||Pn,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){J(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(B,"CONNECTING",{enumerable:!0,value:Ee.indexOf("CONNECTING")});Object.defineProperty(B.prototype,"CONNECTING",{enumerable:!0,value:Ee.indexOf("CONNECTING")});Object.defineProperty(B,"OPEN",{enumerable:!0,value:Ee.indexOf("OPEN")});Object.defineProperty(B.prototype,"OPEN",{enumerable:!0,value:Ee.indexOf("OPEN")});Object.defineProperty(B,"CLOSING",{enumerable:!0,value:Ee.indexOf("CLOSING")});Object.defineProperty(B.prototype,"CLOSING",{enumerable:!0,value:Ee.indexOf("CLOSING")});Object.defineProperty(B,"CLOSED",{enumerable:!0,value:Ee.indexOf("CLOSED")});Object.defineProperty(B.prototype,"CLOSED",{enumerable:!0,value:Ee.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(B.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(B.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Yr])return e[Ud];return null},set(e){for(let n of this.listeners(t))if(n[Yr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Yr]:!0})}})});B.prototype.addEventListener=jd;B.prototype.removeEventListener=qd;$o.exports=B;function Oo(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Dd,protocolVersion:zr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!zr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${zr.join(", ")})`);let i;if(e instanceof Gr)i=e;else try{i=new Gr(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 y=new SyntaxError(l);if(t._redirects===0)throw y;An(t,y);return}let c=o?443:80,u=Od(16).toString("base64"),p=o?Rd.request:Pd.request,g=new Set,f;if(s.createConnection=s.createConnection||(o?Yd:Gd),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&&(f=new Ie(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Kd({[Ie.extensionName]:f.offer()})),n.length){for(let y of n){if(typeof y!="string"||!Vd.test(y)||g.has(y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");g.add(y)}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 y=s.path.split(":");s.socketPath=y[0],s.path=y[1]}let h;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let y=r&&r.headers;if(r={...r,headers:{}},y)for(let[_,w]of Object.entries(y))r.headers[_.toLowerCase()]=w}else if(t.listenerCount("redirect")===0){let y=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!y||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,y||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=p(s),t._redirects&&t.emit("redirect",t.url,h)}else h=t._req=p(s);s.timeout&&h.on("timeout",()=>{J(t,h,"Opening handshake has timed out")}),h.on("error",y=>{h===null||h[Ao]||(h=t._req=null,An(t,y))}),h.on("response",y=>{let _=y.headers.location,w=y.statusCode;if(_&&s.followRedirects&&w>=300&&w<400){if(++t._redirects>s.maxRedirects){J(t,h,"Maximum redirects exceeded");return}h.abort();let I;try{I=new Gr(_,e)}catch{let k=new SyntaxError(`Invalid URL: ${_}`);An(t,k);return}Oo(t,I,n,r)}else t.emit("unexpected-response",h,y)||J(t,h,`Unexpected server response: ${y.statusCode}`)}),h.on("upgrade",(y,_,w)=>{if(t.emit("upgrade",y),t.readyState!==B.CONNECTING)return;h=t._req=null;let I=y.headers.upgrade;if(I===void 0||I.toLowerCase()!=="websocket"){J(t,_,"Invalid Upgrade header");return}let A=Nd("sha1").update(u+$d).digest("base64");if(y.headers["sec-websocket-accept"]!==A){J(t,_,"Invalid Sec-WebSocket-Accept header");return}let k=y.headers["sec-websocket-protocol"],b;if(k!==void 0?g.size?g.has(k)||(b="Server sent an invalid subprotocol"):b="Server sent a subprotocol but none was requested":g.size&&(b="Server sent no subprotocol"),b){J(t,_,b);return}k&&(t._protocol=k);let T=y.headers["sec-websocket-extensions"];if(T!==void 0){if(!f){J(t,_,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let E;try{E=Wd(T)}catch{J(t,_,"Invalid Sec-WebSocket-Extensions header");return}let x=Object.keys(E);if(x.length!==1||x[0]!==Ie.extensionName){J(t,_,"Server indicated an extension that was not requested");return}try{f.accept(E[Ie.extensionName])}catch{J(t,_,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Ie.extensionName]=f}t.setSocket(_,w,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(h,t):h.end()}function An(t,e){t._readyState=B.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Gd(t){return t.path=t.socketPath,Ro.connect(t)}function Yd(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Ro.isIP(t.host)?"":t.host),Ad.connect(t)}function J(t,e,n){t._readyState=B.CLOSING;let r=new Error(n);Error.captureStackTrace(r,J),e.setHeader?(e[Ao]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(An,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Jr(t,e,n){if(e){let r=Md(e)?e.size:Hd(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Ee[t.readyState]})`);process.nextTick(n,r)}}function zd(t,e){let n=this[j];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[j]!==void 0&&(n._socket.removeListener("data",On),process.nextTick(No,n._socket),t===1005?n.close():n.close(t,e))}function Jd(){let t=this[j];t.isPaused||t._socket.resume()}function Qd(t){let e=this[j];e._socket[j]!==void 0&&(e._socket.removeListener("data",On),process.nextTick(No,e._socket),e.close(t[Fd])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function xo(){this[j].emitClose()}function Zd(t,e){this[j].emit("message",t,e)}function Xd(t){let e=this[j];e._autoPong&&e.pong(t,!this._isServer,Po),e.emit("ping",t)}function ef(t){this[j].emit("pong",t)}function No(t){t.resume()}function tf(t){let e=this[j];e.readyState!==B.CLOSED&&(e.readyState===B.OPEN&&(e._readyState=B.CLOSING,Lo(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Lo(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Bo(){let t=this[j];if(this.removeListener("close",Bo),this.removeListener("data",On),this.removeListener("end",Mo),t._readyState=B.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[j]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",xo),t._receiver.on("finish",xo))}function On(t){this[j]._receiver.write(t)||this.pause()}function Mo(){let t=this[j];t._readyState=B.CLOSING,t._receiver.end(),this.end()}function Do(){let t=this[j];this.removeListener("error",Do),this.on("error",Po),t&&(t._readyState=B.CLOSING,this.destroy())}});var qo=S((Oy,jo)=>{"use strict";var Ay=Nn(),{Duplex:nf}=C("stream");function Uo(t){t.emit("close")}function rf(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Fo(t){this.removeListener("error",Fo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function sf(t,e){let n=!0,r=new nf({...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(Uo,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(Uo,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",rf),r.on("error",Fo),r}jo.exports=sf});var Wo=S((Ny,Ko)=>{"use strict";var{tokenChars:of}=pt();function af(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&&of[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}Ko.exports={parse:af}});var Qo=S((By,Jo)=>{"use strict";var lf=C("events"),Ln=C("http"),{Duplex:Ly}=C("stream"),{createHash:cf}=C("crypto"),Ho=Vr(),Ge=Kt(),uf=Wo(),df=Nn(),{CLOSE_TIMEOUT:ff,GUID:pf,kWebSocket:hf}=_e(),gf=/^[+/0-9A-Za-z]{22}==$/,Vo=0,Go=1,zo=2,Qr=class extends lf{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ff,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:df,...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=Ln.createServer((r,s)=>{let i=Ln.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=mf(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=Vo}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===zo){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Gt,this);return}if(e&&this.once("close",e),this._state!==Go)if(this._state=Go,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(Gt,this):process.nextTick(Gt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Gt(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",Yo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ye(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Ye(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!gf.test(i)){Ye(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ye(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Yt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=uf.parse(l)}catch{Ye(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&u!==void 0){let g=new Ge(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let f=Ho.parse(u);f[Ge.extensionName]&&(g.accept(f[Ge.extensionName]),p[Ge.extensionName]=g)}catch{Ye(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let g={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(g,(f,h,y,_)=>{if(!f)return Yt(n,h||401,y,_);this.completeUpgrade(p,i,c,e,n,r,s)});return}if(!this.options.verifyClient(g))return Yt(n,401)}this.completeUpgrade(p,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[hf])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Vo)return Yt(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${cf("sha1").update(n+pf).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),u._protocol=p)}if(e[Ge.extensionName]){let p=e[Ge.extensionName].params,g=Ho.format({[Ge.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${g}`),u._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
6
|
+
`,s)}while(r!==-1);return i+=t.slice(s),i}var Ki=j(()=>{});function qt(t){return nd(t)}var Wi,Hi,xr,ct,jt,Vi,ut,td,nd,Rr,rd,sd,Pr,En,id,od,By,m,dt=j(()=>{Mi();Fi();Ki();({stdout:Wi,stderr:Hi}=Ui),xr=Symbol("GENERATOR"),ct=Symbol("STYLER"),jt=Symbol("IS_EMPTY"),Vi=["ansi","ansi","ansi256","ansi16m"],ut=Object.create(null),td=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let n=Wi?Wi.level:0;t.level=e.level===void 0?n:e.level},nd=t=>{let e=(...n)=>n.join(" ");return td(e,t),Object.setPrototypeOf(e,qt.prototype),e};Object.setPrototypeOf(qt.prototype,Function.prototype);for(let[t,e]of Object.entries(ie))ut[t]={get(){let n=En(this,Pr(e.open,e.close,this[ct]),this[jt]);return Object.defineProperty(this,t,{value:n}),n}};ut.visible={get(){let t=En(this,this[ct],!0);return Object.defineProperty(this,"visible",{value:t}),t}};Rr=(t,e,n,...r)=>t==="rgb"?e==="ansi16m"?ie[n].ansi16m(...r):e==="ansi256"?ie[n].ansi256(ie.rgbToAnsi256(...r)):ie[n].ansi(ie.rgbToAnsi(...r)):t==="hex"?Rr("rgb",e,n,...ie.hexToRgb(...r)):ie[n][t](...r),rd=["rgb","hex","ansi256"];for(let t of rd){ut[t]={get(){let{level:n}=this;return function(...r){let s=Pr(Rr(t,Vi[n],"color",...r),ie.color.close,this[ct]);return En(this,s,this[jt])}}};let e="bg"+t[0].toUpperCase()+t.slice(1);ut[e]={get(){let{level:n}=this;return function(...r){let s=Pr(Rr(t,Vi[n],"bgColor",...r),ie.bgColor.close,this[ct]);return En(this,s,this[jt])}}}}sd=Object.defineProperties(()=>{},{...ut,level:{enumerable:!0,get(){return this[xr].level},set(t){this[xr].level=t}}}),Pr=(t,e,n)=>{let r,s;return n===void 0?(r=t,s=e):(r=n.openAll+t,s=e+n.closeAll),{open:t,close:e,openAll:r,closeAll:s,parent:n}},En=(t,e,n)=>{let r=(...s)=>id(r,s.length===1?""+s[0]:s.join(" "));return Object.setPrototypeOf(r,sd),r[xr]=t,r[ct]=e,r[jt]=n,r},id=(t,e)=>{if(t.level<=0||!e)return t[jt]?"":e;let n=t[ct];if(n===void 0)return e;let{openAll:r,closeAll:s}=n;if(e.includes("\x1B"))for(;n!==void 0;)e=ji(e,n.close,n.open),n=n.parent;let i=e.indexOf(`
|
|
7
|
+
`);return i!==-1&&(e=qi(e,s,r,i)),r+e+s};Object.defineProperties(qt.prototype,ut);od=qt(),By=qt({level:Hi?Hi.level:0}),m=od});var bn,Gi=j(()=>{"use strict";bn=class{state="disconnected";context={consecutiveFailures:0,reconnectDelay:1e3,disconnectReason:"none",wasSleeping:!1};transition(e){let n=this.state,r=this._nextState(n,e);if(r===void 0)throw new Error(`Invalid transition: ${e.type} from state "${n}"`);return this.state=r,r}reset(){this.state="disconnected",this.context={consecutiveFailures:0,reconnectDelay:1e3,disconnectReason:"none",wasSleeping:!1}}get connectionPhase(){switch(this.state){case"disconnected":case"connecting":case"registering":return"registering";case"pairing":case"setup_reconnecting":case"setup_pairing":return"pairing";case"paired":return"paired";case"paired_sleeping":return"paired_sleeping";case"reconnecting":return"paired"}}get inSetupMode(){return this.state==="setup_reconnecting"||this.state==="setup_pairing"}get disconnectedByRemote(){return this.context.disconnectReason==="remote"}_nextState(e,n){switch(e){case"disconnected":return this._fromDisconnected(n);case"connecting":return this._fromConnecting(n);case"registering":return this._fromRegistering(n);case"pairing":return this._fromPairing(n);case"paired":return this._fromPaired(n);case"paired_sleeping":return this._fromPairedSleeping(n);case"reconnecting":return this._fromReconnecting(n);case"setup_reconnecting":return this._fromSetupReconnecting(n);case"setup_pairing":return this._fromSetupPairing(n)}}_fromDisconnected(e){switch(e.type){case"CONNECT":return this.context.disconnectReason="none","connecting";case"ENTER_SETUP":return this.context.disconnectReason="none",e.hasSavedState?"setup_reconnecting":"setup_pairing";case"FORCE_DISCONNECT":return"disconnected"}}_fromConnecting(e){switch(e.type){case"WS_OPEN":return this.context.consecutiveFailures=0,this.context.reconnectDelay=1e3,"registering";case"WS_CLOSE":return"reconnecting"}}_fromRegistering(e){switch(e.type){case"REGISTERED":return e.hasSharedSecret&&this.context.wasSleeping?(this.context.wasSleeping=!1,"paired_sleeping"):e.hasSharedSecret?"paired":"pairing";case"WS_CLOSE":return"reconnecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected"}}_fromPairing(e){switch(e.type){case"PAIRED":return"paired";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected";case"WS_CLOSE":return this.context.disconnectReason="network","disconnected"}}_fromPaired(e){switch(e.type){case"WS_CLOSE":return"reconnecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected";case"SLEEP":return"paired_sleeping"}}_fromPairedSleeping(e){switch(e.type){case"WAKE":return"paired";case"WS_CLOSE":return this.context.wasSleeping=!0,"reconnecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote",this.context.wasSleeping=!1,"disconnected";case"SLEEP":return"paired_sleeping"}}_fromReconnecting(e){switch(e.type){case"RECONNECT_TIMER":return"connecting";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected"}}_fromSetupReconnecting(e){switch(e.type){case"PAIRED":return"paired";case"SETUP_RECONNECT_FAILED":return"setup_pairing";case"CONNECT":return"setup_reconnecting";case"WS_OPEN":return"setup_reconnecting";case"WS_CLOSE":return"setup_reconnecting";case"REGISTERED":return e.hasSharedSecret&&this.context.wasSleeping?(this.context.wasSleeping=!1,"paired_sleeping"):e.hasSharedSecret?"paired":"setup_pairing"}}_fromSetupPairing(e){switch(e.type){case"PAIRED":return"paired";case"FORCE_DISCONNECT":return this.context.disconnectReason="remote","disconnected";case"CONNECT":return"setup_pairing";case"WS_OPEN":return"setup_pairing";case"WS_CLOSE":return"setup_pairing";case"REGISTERED":return"setup_pairing"}}}});function Yi(t){Ar=t}function Ji(){d.machine.reset(),d.ws=null,d.heartbeatTimer=null,d.deviceId="",d.deviceToken="",d.ownKeyPair=null,d.peerPublicKey=null,d.sharedSecret=null,d.peerAppVersion=null,d.peerCapabilities=[],d.lastMessageAt=0,d.verifyCodeResolve=null,d.registeredResolve=null,d.shuttingDown=!1,d.wakeExpiresAt=null,d.wakeTimer=null,d.wakeLockout={failedAttempts:0,lockedUntil:null}}var z,Ar,zi,Or,d,ft=j(()=>{"use strict";Gi();z="1.10.10",Ar="wss://relay.beachviber.com";zi=3e4,Or=3e4,d={machine:new bn,ws:null,heartbeatTimer:null,projects:[],deviceId:"",deviceToken:"",get connectionPhase(){return this.machine.connectionPhase},get inSetupMode(){return this.machine.inSetupMode},get disconnectedByRemote(){return this.machine.disconnectedByRemote},get consecutiveFailures(){return this.machine.context.consecutiveFailures},get reconnectDelay(){return this.machine.context.reconnectDelay},ownKeyPair:null,peerPublicKey:null,sharedSecret:null,peerAppVersion:null,peerCapabilities:[],lastMessageAt:0,verifyCodeResolve:null,registeredResolve:null,enterSetupMode:null,shuttingDown:!1,get wakeState(){return this.machine.state==="paired_sleeping"?"sleeping":"awake"},wakeExpiresAt:null,wakeTimer:null,wakeLockout:{failedAttempts:0,lockedUntil:null},onSleepTransition:null}});var we=S((Fy,Xi)=>{"use strict";var Qi=["nodebuffer","arraybuffer","fragments"],Zi=typeof Blob<"u";Zi&&Qi.push("blob");Xi.exports={BINARY_TYPES:Qi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Zi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Kt=S((jy,Tn)=>{"use strict";var{EMPTY_BUFFER:ad}=we(),Nr=Buffer[Symbol.species];function ld(t,e){if(t.length===0)return ad;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 Nr(n.buffer,n.byteOffset,r):n}function eo(t,e,n,r,s){for(let i=0;i<s;i++)n[r+i]=t[i]^e[i&3]}function to(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function cd(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Lr(t){if(Lr.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Nr(t):ArrayBuffer.isView(t)?e=new Nr(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Lr.readOnly=!1),e}Tn.exports={concat:ld,mask:eo,toArrayBuffer:cd,toBuffer:Lr,unmask:to};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=C("bufferutil");Tn.exports.mask=function(e,n,r,s,i){i<48?eo(e,n,r,s,i):t.mask(e,n,r,s,i)},Tn.exports.unmask=function(e,n){e.length<32?to(e,n):t.unmask(e,n)}}catch{}});var so=S((qy,ro)=>{"use strict";var no=Symbol("kDone"),Br=Symbol("kRun"),Mr=class{constructor(e){this[no]=()=>{this.pending--,this[Br]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Br]()}[Br](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[no])}}};ro.exports=Mr});var Ht=S((Ky,lo)=>{"use strict";var Wt=C("zlib"),io=Kt(),ud=so(),{kStatusCode:oo}=we(),dd=Buffer[Symbol.species],fd=Buffer.from([0,0,255,255]),vn=Symbol("permessage-deflate"),Se=Symbol("total-length"),pt=Symbol("callback"),Ie=Symbol("buffers"),ht=Symbol("error"),kn,Dr=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,!kn){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;kn=new ud(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[pt];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){kn.add(s=>{this._decompress(e,n,(i,o)=>{s(),r(i,o)})})}compress(e,n,r){kn.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"?Wt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Wt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[vn]=this,this._inflate[Se]=0,this._inflate[Ie]=[],this._inflate.on("error",hd),this._inflate.on("data",ao)}this._inflate[pt]=r,this._inflate.write(e),n&&this._inflate.write(fd),this._inflate.flush(()=>{let i=this._inflate[ht];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=io.concat(this._inflate[Ie],this._inflate[Se]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Se]=0,this._inflate[Ie]=[],n&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Wt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Wt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Se]=0,this._deflate[Ie]=[],this._deflate.on("data",pd)}this._deflate[pt]=r,this._deflate.write(e),this._deflate.flush(Wt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=io.concat(this._deflate[Ie],this._deflate[Se]);n&&(i=new dd(i.buffer,i.byteOffset,i.length-4)),this._deflate[pt]=null,this._deflate[Se]=0,this._deflate[Ie]=[],n&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};lo.exports=Dr;function pd(t){this[Ie].push(t),this[Se]+=t.length}function ao(t){if(this[Se]+=t.length,this[vn]._maxPayload<1||this[Se]<=this[vn]._maxPayload){this[Ie].push(t);return}this[ht]=new RangeError("Max payload size exceeded"),this[ht].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ht][oo]=1009,this.removeListener("data",ao),this.reset()}function hd(t){if(this[vn]._inflate=null,this[ht]){this[pt](this[ht]);return}t[oo]=1007,this[pt](t)}});var gt=S((Wy,Cn)=>{"use strict";var{isUtf8:co}=C("buffer"),{hasBlob:gd}=we(),md=[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 yd(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function $r(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 _d(t){return gd&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Cn.exports={isBlob:_d,isValidStatusCode:yd,isValidUTF8:$r,tokenChars:md};if(co)Cn.exports.isValidUTF8=function(t){return t.length<24?$r(t):co(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=C("utf-8-validate");Cn.exports.isValidUTF8=function(e){return e.length<32?$r(e):t(e)}}catch{}});var Kr=S((Hy,yo)=>{"use strict";var{Writable:wd}=C("stream"),uo=Ht(),{BINARY_TYPES:Sd,EMPTY_BUFFER:fo,kStatusCode:Ed,kWebSocket:bd}=we(),{concat:Ur,toArrayBuffer:Td,unmask:kd}=Kt(),{isValidStatusCode:vd,isValidUTF8:po}=gt(),In=Buffer[Symbol.species],X=0,ho=1,go=2,mo=3,Fr=4,jr=5,xn=6,qr=class extends wd{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Sd[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[bd]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=X}_write(e,n,r){if(this._opcode===8&&this._state==X)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new In(r.buffer,r.byteOffset+e,r.length-e),new In(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 In(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case X:this.getInfo(e);break;case ho:this.getPayloadLength16(e);break;case go:this.getPayloadLength64(e);break;case mo:this.getMask();break;case Fr:this.getData(e);break;case jr:case xn: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[uo.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=ho:this._payloadLength===127?this._state=go: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=mo:this._state=Fr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Fr}getData(e){let n=fo;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&&kd(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=jr,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[uo.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return n(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(o);return}this._fragments.push(i)}this.dataMessage(n),this._state===X&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=X;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Ur(r,n):this._binaryType==="arraybuffer"?s=Td(Ur(r,n)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=X):(this._state=xn,setImmediate(()=>{this.emit("message",s,!0),this._state=X,this.startLoop(e)}))}else{let s=Ur(r,n);if(!this._skipUTF8Validation&&!po(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===jr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=X):(this._state=xn,setImmediate(()=>{this.emit("message",s,!1),this._state=X,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,fo),this.end();else{let r=e.readUInt16BE(0);if(!vd(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(i);return}let s=new In(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!po(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=X;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=X):(this._state=xn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=X,this.startLoop(n)}))}createError(e,n,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=i,o[Ed]=s,o}};yo.exports=qr});var Vr=S((Gy,So)=>{"use strict";var{Duplex:Vy}=C("stream"),{randomFillSync:Cd}=C("crypto"),_o=Ht(),{EMPTY_BUFFER:Id,kWebSocket:xd,NOOP:Rd}=we(),{isBlob:mt,isValidStatusCode:Pd}=gt(),{mask:wo,toBuffer:He}=Kt(),ee=Symbol("kByteLength"),Ad=Buffer.alloc(4),Rn=8*1024,Ve,yt=Rn,oe=0,Od=1,Nd=2,Wr=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=oe,this.onerror=Rd,this[xd]=void 0}static frame(e,n){let r,s=!1,i=2,o=!1;n.mask&&(r=n.maskBuffer||Ad,n.generateMask?n.generateMask(r):(yt===Rn&&(Ve===void 0&&(Ve=Buffer.alloc(Rn)),Cd(Ve,0,Rn),yt=0),r[0]=Ve[yt++],r[1]=Ve[yt++],r[2]=Ve[yt++],r[3]=Ve[yt++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!n.mask||o)&&n[ee]!==void 0?a=n[ee]:(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?(wo(e,r,c,i,a),[c]):(wo(e,r,e,0,a),[c,e])):[c,e]}close(e,n,r,s){let i;if(e===void 0)i=Id;else{if(typeof e!="number"||!Pd(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={[ee]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==oe?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):mt(e)?(s=e.size,i=!1):(e=He(e),s=e.length,i=He.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ee]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};mt(e)?this._state!==oe?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==oe?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):mt(e)?(s=e.size,i=!1):(e=He(e),s=e.length,i=He.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ee]:s,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};mt(e)?this._state!==oe?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==oe?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let s=this._extensions[_o.extensionName],i=n.binary?2:1,o=n.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):mt(e)?(a=e.size,l=!1):(e=He(e),a=e.length,l=He.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),n.fin&&(this._firstFragment=!0);let c={[ee]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};mt(e)?this._state!==oe?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==oe?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,n,r,s){this._bufferedBytes+=r[ee],this._state=Nd,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Hr,this,a,s);return}this._bufferedBytes-=r[ee];let o=He(i);n?this.dispatch(o,n,r,s):(this._state=oe,this.sendFrame(t.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Ld,this,i,s)})}dispatch(e,n,r,s){if(!n){this.sendFrame(t.frame(e,r),s);return}let i=this._extensions[_o.extensionName];this._bufferedBytes+=r[ee],this._state=Od,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Hr(this,l,s);return}this._bufferedBytes-=r[ee],this._state=oe,r.readOnly=!1,this.sendFrame(t.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===oe&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ee],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ee],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)}};So.exports=Wr;function Hr(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 Ld(t,e,n){Hr(t,e,n),t.onerror(e)}});var Ro=S((Yy,xo)=>{"use strict";var{kForOnEventAttribute:Vt,kListener:Gr}=we(),Eo=Symbol("kCode"),bo=Symbol("kData"),To=Symbol("kError"),ko=Symbol("kMessage"),vo=Symbol("kReason"),_t=Symbol("kTarget"),Co=Symbol("kType"),Io=Symbol("kWasClean"),Ee=class{constructor(e){this[_t]=null,this[Co]=e}get target(){return this[_t]}get type(){return this[Co]}};Object.defineProperty(Ee.prototype,"target",{enumerable:!0});Object.defineProperty(Ee.prototype,"type",{enumerable:!0});var Ge=class extends Ee{constructor(e,n={}){super(e),this[Eo]=n.code===void 0?0:n.code,this[vo]=n.reason===void 0?"":n.reason,this[Io]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Eo]}get reason(){return this[vo]}get wasClean(){return this[Io]}};Object.defineProperty(Ge.prototype,"code",{enumerable:!0});Object.defineProperty(Ge.prototype,"reason",{enumerable:!0});Object.defineProperty(Ge.prototype,"wasClean",{enumerable:!0});var wt=class extends Ee{constructor(e,n={}){super(e),this[To]=n.error===void 0?null:n.error,this[ko]=n.message===void 0?"":n.message}get error(){return this[To]}get message(){return this[ko]}};Object.defineProperty(wt.prototype,"error",{enumerable:!0});Object.defineProperty(wt.prototype,"message",{enumerable:!0});var Gt=class extends Ee{constructor(e,n={}){super(e),this[bo]=n.data===void 0?null:n.data}get data(){return this[bo]}};Object.defineProperty(Gt.prototype,"data",{enumerable:!0});var Bd={addEventListener(t,e,n={}){for(let s of this.listeners(t))if(!n[Vt]&&s[Gr]===e&&!s[Vt])return;let r;if(t==="message")r=function(i,o){let a=new Gt("message",{data:o?i:i.toString()});a[_t]=this,Pn(e,this,a)};else if(t==="close")r=function(i,o){let a=new Ge("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[_t]=this,Pn(e,this,a)};else if(t==="error")r=function(i){let o=new wt("error",{error:i,message:i.message});o[_t]=this,Pn(e,this,o)};else if(t==="open")r=function(){let i=new Ee("open");i[_t]=this,Pn(e,this,i)};else return;r[Vt]=!!n[Vt],r[Gr]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[Gr]===e&&!n[Vt]){this.removeListener(t,n);break}}};xo.exports={CloseEvent:Ge,ErrorEvent:wt,Event:Ee,EventTarget:Bd,MessageEvent:Gt};function Pn(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Yr=S((zy,Po)=>{"use strict";var{tokenChars:Yt}=gt();function de(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function Md(t){let e=Object.create(null),n=Object.create(null),r=!1,s=!1,i=!1,o,a,l=-1,c=-1,u=-1,p=0;for(;p<t.length;p++)if(c=t.charCodeAt(p),o===void 0)if(u===-1&&Yt[c]===1)l===-1&&(l=p);else if(p!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let f=t.slice(l,u);c===44?(de(e,f,n),n=Object.create(null)):o=f,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(u===-1&&Yt[c]===1)l===-1&&(l=p);else if(c===32||c===9)u===-1&&l!==-1&&(u=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p),de(n,t.slice(l,u),!0),c===44&&(de(e,o,n),n=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,p),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(s){if(Yt[c]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);l===-1?l=p:r||(r=!0),s=!1}else if(i)if(Yt[c]===1)l===-1&&(l=p);else if(c===34&&l!==-1)i=!1,u=p;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===34&&t.charCodeAt(p-1)===61)i=!0;else if(u===-1&&Yt[c]===1)l===-1&&(l=p);else if(l!==-1&&(c===32||c===9))u===-1&&(u=p);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let f=t.slice(l,u);r&&(f=f.replace(/\\/g,""),r=!1),de(n,a,f),c===44&&(de(e,o,n),n=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=p);let g=t.slice(l,u);return o===void 0?de(e,g,n):(a===void 0?de(n,g,!0):r?de(n,a,g.replace(/\\/g,"")):de(n,a,g),de(e,o,n)),e}function Dd(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(", ")}Po.exports={format:Dd,parse:Md}});var Ln=S((Zy,qo)=>{"use strict";var $d=C("events"),Ud=C("https"),Fd=C("http"),No=C("net"),jd=C("tls"),{randomBytes:qd,createHash:Kd}=C("crypto"),{Duplex:Jy,Readable:Qy}=C("stream"),{URL:zr}=C("url"),xe=Ht(),Wd=Kr(),Hd=Vr(),{isBlob:Vd}=gt(),{BINARY_TYPES:Ao,CLOSE_TIMEOUT:Gd,EMPTY_BUFFER:An,GUID:Yd,kForOnEventAttribute:Jr,kListener:zd,kStatusCode:Jd,kWebSocket:q,NOOP:Lo}=we(),{EventTarget:{addEventListener:Qd,removeEventListener:Zd}}=Ro(),{format:Xd,parse:ef}=Yr(),{toBuffer:tf}=Kt(),Bo=Symbol("kAborted"),Qr=[8,13],be=["CONNECTING","OPEN","CLOSING","CLOSED"],nf=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,B=class t extends $d{constructor(e,n,r){super(),this._binaryType=Ao[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=An,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]),Mo(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ao.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 Wd({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Hd(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[q]=this,i[q]=this,e[q]=this,s.on("conclude",of),s.on("drain",af),s.on("error",lf),s.on("message",cf),s.on("ping",uf),s.on("pong",df),i.onerror=ff,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Uo),e.on("data",Nn),e.on("end",Fo),e.on("error",jo),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[xe.extensionName]&&this._extensions[xe.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){J(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())}),$o(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){Zr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||An,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){Zr(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||An,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){Zr(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[xe.extensionName]||(s.compress=!1),this._sender.send(e||An,s,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){J(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(B,"CONNECTING",{enumerable:!0,value:be.indexOf("CONNECTING")});Object.defineProperty(B.prototype,"CONNECTING",{enumerable:!0,value:be.indexOf("CONNECTING")});Object.defineProperty(B,"OPEN",{enumerable:!0,value:be.indexOf("OPEN")});Object.defineProperty(B.prototype,"OPEN",{enumerable:!0,value:be.indexOf("OPEN")});Object.defineProperty(B,"CLOSING",{enumerable:!0,value:be.indexOf("CLOSING")});Object.defineProperty(B.prototype,"CLOSING",{enumerable:!0,value:be.indexOf("CLOSING")});Object.defineProperty(B,"CLOSED",{enumerable:!0,value:be.indexOf("CLOSED")});Object.defineProperty(B.prototype,"CLOSED",{enumerable:!0,value:be.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(B.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(B.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Jr])return e[zd];return null},set(e){for(let n of this.listeners(t))if(n[Jr]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Jr]:!0})}})});B.prototype.addEventListener=Qd;B.prototype.removeEventListener=Zd;qo.exports=B;function Mo(t,e,n,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Gd,protocolVersion:Qr[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,!Qr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Qr.join(", ")})`);let i;if(e instanceof zr)i=e;else try{i=new zr(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 y=new SyntaxError(l);if(t._redirects===0)throw y;On(t,y);return}let c=o?443:80,u=qd(16).toString("base64"),p=o?Ud.request:Fd.request,g=new Set,f;if(s.createConnection=s.createConnection||(o?sf:rf),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&&(f=new xe(s.perMessageDeflate!==!0?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=Xd({[xe.extensionName]:f.offer()})),n.length){for(let y of n){if(typeof y!="string"||!nf.test(y)||g.has(y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");g.add(y)}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 y=s.path.split(":");s.socketPath=y[0],s.path=y[1]}let h;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?s.socketPath:i.host;let y=r&&r.headers;if(r={...r,headers:{}},y)for(let[_,w]of Object.entries(y))r.headers[_.toLowerCase()]=w}else if(t.listenerCount("redirect")===0){let y=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:i.host===t._originalHostOrSocketPath;(!y||t._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,y||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=p(s),t._redirects&&t.emit("redirect",t.url,h)}else h=t._req=p(s);s.timeout&&h.on("timeout",()=>{J(t,h,"Opening handshake has timed out")}),h.on("error",y=>{h===null||h[Bo]||(h=t._req=null,On(t,y))}),h.on("response",y=>{let _=y.headers.location,w=y.statusCode;if(_&&s.followRedirects&&w>=300&&w<400){if(++t._redirects>s.maxRedirects){J(t,h,"Maximum redirects exceeded");return}h.abort();let x;try{x=new zr(_,e)}catch{let E=new SyntaxError(`Invalid URL: ${_}`);On(t,E);return}Mo(t,x,n,r)}else t.emit("unexpected-response",h,y)||J(t,h,`Unexpected server response: ${y.statusCode}`)}),h.on("upgrade",(y,_,w)=>{if(t.emit("upgrade",y),t.readyState!==B.CONNECTING)return;h=t._req=null;let x=y.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){J(t,_,"Invalid Upgrade header");return}let A=Kd("sha1").update(u+Yd).digest("base64");if(y.headers["sec-websocket-accept"]!==A){J(t,_,"Invalid Sec-WebSocket-Accept header");return}let E=y.headers["sec-websocket-protocol"],T;if(E!==void 0?g.size?g.has(E)||(T="Server sent an invalid subprotocol"):T="Server sent a subprotocol but none was requested":g.size&&(T="Server sent no subprotocol"),T){J(t,_,T);return}E&&(t._protocol=E);let k=y.headers["sec-websocket-extensions"];if(k!==void 0){if(!f){J(t,_,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let b;try{b=ef(k)}catch{J(t,_,"Invalid Sec-WebSocket-Extensions header");return}let I=Object.keys(b);if(I.length!==1||I[0]!==xe.extensionName){J(t,_,"Server indicated an extension that was not requested");return}try{f.accept(b[xe.extensionName])}catch{J(t,_,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[xe.extensionName]=f}t.setSocket(_,w,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(h,t):h.end()}function On(t,e){t._readyState=B.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function rf(t){return t.path=t.socketPath,No.connect(t)}function sf(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=No.isIP(t.host)?"":t.host),jd.connect(t)}function J(t,e,n){t._readyState=B.CLOSING;let r=new Error(n);Error.captureStackTrace(r,J),e.setHeader?(e[Bo]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(On,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Zr(t,e,n){if(e){let r=Vd(e)?e.size:tf(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${be[t.readyState]})`);process.nextTick(n,r)}}function of(t,e){let n=this[q];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[q]!==void 0&&(n._socket.removeListener("data",Nn),process.nextTick(Do,n._socket),t===1005?n.close():n.close(t,e))}function af(){let t=this[q];t.isPaused||t._socket.resume()}function lf(t){let e=this[q];e._socket[q]!==void 0&&(e._socket.removeListener("data",Nn),process.nextTick(Do,e._socket),e.close(t[Jd])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Oo(){this[q].emitClose()}function cf(t,e){this[q].emit("message",t,e)}function uf(t){let e=this[q];e._autoPong&&e.pong(t,!this._isServer,Lo),e.emit("ping",t)}function df(t){this[q].emit("pong",t)}function Do(t){t.resume()}function ff(t){let e=this[q];e.readyState!==B.CLOSED&&(e.readyState===B.OPEN&&(e._readyState=B.CLOSING,$o(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function $o(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Uo(){let t=this[q];if(this.removeListener("close",Uo),this.removeListener("data",Nn),this.removeListener("end",Fo),t._readyState=B.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[q]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Oo),t._receiver.on("finish",Oo))}function Nn(t){this[q]._receiver.write(t)||this.pause()}function Fo(){let t=this[q];t._readyState=B.CLOSING,t._receiver.end(),this.end()}function jo(){let t=this[q];this.removeListener("error",jo),this.on("error",Lo),t&&(t._readyState=B.CLOSING,this.destroy())}});var Vo=S((e_,Ho)=>{"use strict";var Xy=Ln(),{Duplex:pf}=C("stream");function Ko(t){t.emit("close")}function hf(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Wo(t){this.removeListener("error",Wo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function gf(t,e){let n=!0,r=new pf({...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(Ko,r);return}let o=!1;t.once("error",function(l){o=!0,i(l)}),t.once("close",function(){o||i(s),process.nextTick(Ko,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",hf),r.on("error",Wo),r}Ho.exports=gf});var Yo=S((t_,Go)=>{"use strict";var{tokenChars:mf}=gt();function yf(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&&mf[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}Go.exports={parse:yf}});var ta=S((r_,ea)=>{"use strict";var _f=C("events"),Bn=C("http"),{Duplex:n_}=C("stream"),{createHash:wf}=C("crypto"),zo=Yr(),Ye=Ht(),Sf=Yo(),Ef=Ln(),{CLOSE_TIMEOUT:bf,GUID:Tf,kWebSocket:kf}=we(),vf=/^[+/0-9A-Za-z]{22}==$/,Jo=0,Qo=1,Xo=2,Xr=class extends _f{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:bf,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Ef,...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=Bn.createServer((r,s)=>{let i=Bn.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=Cf(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=Jo}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===Xo){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(zt,this);return}if(e&&this.once("close",e),this._state!==Qo)if(this._state=Qo,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(zt,this):process.nextTick(zt,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{zt(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",Zo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ze(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){ze(this,e,n,400,"Invalid Upgrade header");return}if(i===void 0||!vf.test(i)){ze(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ze(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Jt(n,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Sf.parse(l)}catch{ze(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&u!==void 0){let g=new Ye(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let f=zo.parse(u);f[Ye.extensionName]&&(g.accept(f[Ye.extensionName]),p[Ye.extensionName]=g)}catch{ze(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let g={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(g,(f,h,y,_)=>{if(!f)return Jt(n,h||401,y,_);this.completeUpgrade(p,i,c,e,n,r,s)});return}if(!this.options.verifyClient(g))return Jt(n,401)}this.completeUpgrade(p,i,c,e,n,r,s)}completeUpgrade(e,n,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[kf])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Jo)return Jt(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${wf("sha1").update(n+Tf).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;p&&(c.push(`Sec-WebSocket-Protocol: ${p}`),u._protocol=p)}if(e[Ye.extensionName]){let p=e[Ye.extensionName].params,g=zo.format({[Ye.extensionName]:[p]});c.push(`Sec-WebSocket-Extensions: ${g}`),u._extensions=e}this.emit("headers",c,s),i.write(c.concat(`\r
|
|
8
8
|
`).join(`\r
|
|
9
|
-
`)),i.removeListener("error",
|
|
9
|
+
`)),i.removeListener("error",Zo),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(zt,this)})),a(u,s)}};ea.exports=Xr;function Cf(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 zt(t){t._state=Xo,t.emit("close")}function Zo(){this.destroy()}function Jt(t,e,n,r){n=n||Bn.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} ${Bn.STATUS_CODES[e]}\r
|
|
10
10
|
`+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
|
|
11
11
|
`)+`\r
|
|
12
12
|
\r
|
|
13
|
-
`+n)}function
|
|
14
|
-
`}function
|
|
15
|
-
`).length:0;return{branch:e,lastCommit:n,dirty:s>0,changedFiles:s}}catch{return null}}function
|
|
16
|
-
`))if(l)try{let c=JSON.parse(l);if(c.type==="user"&&c.cwd)return c.cwd}catch{}}catch{continue}return null}function
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
`,{
|
|
20
|
-
|
|
21
|
-
`))if(
|
|
22
|
-
|
|
23
|
-
`,{
|
|
13
|
+
`+n)}function ze(t,e,n,r,s,i){if(t.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,ze),t.emit("wsClientError",o,n,e)}else Jt(n,r,s,i)}});import{appendFileSync as ia,statSync as Af,renameSync as ra,unlinkSync as Of,mkdirSync as Nf}from"fs";import{join as Lf}from"path";function la(t,e){Nf(t,{recursive:!0});let n=`beachviber${e}.log`;if(Re=Lf(t,n),oa=!0,$n.length>0){let r=$n.join("");$n.length=0;try{ia(Re,r)}catch{}}}function ca(t){aa=es[t]}function Mf(){if(!Re)return;let t;try{t=Af(Re).size}catch{return}if(t<Bf)return;let e=Re.lastIndexOf(".log"),n=Re.slice(0,e),r=".log",s=`${n}.${sa}${r}`;try{Of(s)}catch{}for(let i=sa-1;i>=1;i--){let o=`${n}.${i}${r}`,a=`${n}.${i+1}${r}`;try{ra(o,a)}catch{}}try{ra(Re,`${n}.1${r}`)}catch{}}function Mn(t,e,n){let r=new Date().toISOString(),s=t.padEnd(5);return`${r} [${s}] ${e} ${n}
|
|
14
|
+
`}function Dn(t){if(!oa){$n.push(t);return}try{Mf(),ia(Re,t)}catch{}}function M(t){let e=`[${t}]`;return{debug(n){aa>es.DEBUG||Dn(Mn("DEBUG",e,n))},info(n){Dn(Mn("INFO",e,n))},warn(n){Dn(Mn("WARN",e,n))},error(n,r){let s=r!==void 0?` ${r instanceof Error?r.stack||r.message:String(r)}`:"";Dn(Mn("ERROR",e,n+s))}}}var Bf,sa,es,Re,oa,aa,$n,ae=j(()=>{"use strict";Bf=5*1024*1024,sa=3,es={DEBUG:0,INFO:1,WARN:2,ERROR:3},Re=null,oa=!1,aa=es.INFO,$n=[]});import{execFile as Df}from"child_process";import{readFileSync as $f,readdirSync as ns,existsSync as Uf,openSync as Ff,readSync as jf,closeSync as qf}from"fs";import{basename as Kf,join as Un}from"path";import{homedir as Wf}from"os";function ts(t,e){return new Promise((n,r)=>{Df("git",t,{cwd:e,timeout:Hf},(s,i)=>{if(s)return r(s);n(i.trim())})})}async function Vf(t){try{let[e,n,r]=await Promise.all([ts(["rev-parse","--abbrev-ref","HEAD"],t),ts(["log","-1","--oneline"],t),ts(["status","--porcelain"],t)]),s=r?r.split(`
|
|
15
|
+
`).length:0;return{branch:e,lastCommit:n,dirty:s>0,changedFiles:s}}catch{return null}}function rs(t){return`proj_${t.toLowerCase().replace(/[^a-z0-9]/g,"_")}`}async function Fn(t){let e=Kf(t),n=await Vf(t)||{branch:"unknown",lastCommit:"",dirty:!1,changedFiles:0};return{id:rs(e),name:e,path:t,git:n}}async function Et(){let t=Un(Wf(),".claude","projects");if(!Uf(t))return[];let e;try{e=ns(t,{withFileTypes:!0}).filter(s=>s.isDirectory()).map(s=>s.name)}catch{return[]}let n=new Set,r=[];for(let s of e){let i=Un(t,s),o=ss(i);if(o&&!n.has(o)){n.add(o);try{let a=await Fn(o),l=Gf(i);r.push({...a,sessionCount:l})}catch{}}}ua.info(`Discovered ${r.length} projects from ~/.claude/projects/`);for(let s of r)ua.info(` ${s.name} -- ${s.sessionCount} sessions (${s.git.branch})`);return r}function Gf(t){try{return ns(t).filter(e=>e.endsWith(".jsonl")).length}catch{return 0}}function ss(t){let e=Un(t,"sessions-index.json");try{let s=$f(e,"utf-8"),i=JSON.parse(s);if(i.originalPath)return i.originalPath}catch{}let n;try{n=ns(t).filter(s=>s.endsWith(".jsonl"))}catch{return null}let r=Buffer.alloc(4096);for(let s of n)try{let i=Ff(Un(t,s),"r"),o=jf(i,r,0,4096,0);qf(i);let a=r.toString("utf-8",0,o);for(let l of a.split(`
|
|
16
|
+
`))if(l)try{let c=JSON.parse(l);if(c.type==="user"&&c.cwd)return c.cwd}catch{}}catch{continue}return null}function da(t,e){return t.find(n=>n.id===e)}var ua,Hf,jn=j(()=>{"use strict";ae();ua=M("scan"),Hf=5e3});import{appendFileSync as ha,statSync as Yf,renameSync as fa,unlinkSync as zf,mkdirSync as Jf}from"fs";import{join as Qf}from"path";function ma(t,e){try{Jf(t,{recursive:!0});let n=`audit${e}.log`;if(Pe=Qf(t,n),ga=!0,qn.length>0){let r=qn.join("");qn.length=0;try{ha(Pe,r)}catch{}}}catch{}}function Xf(){if(!Pe)return;let t;try{t=Yf(Pe).size}catch{return}if(t<Zf)return;let e=Pe.lastIndexOf(".log"),n=Pe.slice(0,e),r=".log",s=`${n}.${pa}${r}`;try{zf(s)}catch{}for(let i=pa-1;i>=1;i--){let o=`${n}.${i}${r}`,a=`${n}.${i+1}${r}`;try{fa(o,a)}catch{}}try{fa(Pe,`${n}.1${r}`)}catch{}}function U(t,e,n,r,s){try{let i={timestamp:new Date().toISOString(),event:t,category:e,severity:n,detail:r};s!==void 0&&(i.meta=s);let o=JSON.stringify(i)+`
|
|
17
|
+
`;if(!ga){qn.push(o);return}Xf(),ha(Pe,o)}catch{}}var Zf,pa,Pe,ga,qn,Qt=j(()=>{"use strict";Zf=2*1024*1024,pa=5,Pe=null,ga=!1,qn=[]});import{readFileSync as ep,writeFileSync as tp,mkdirSync as np,existsSync as is,unlinkSync as rp}from"fs";import{join as ya}from"path";import{homedir as sp,hostname as ip,platform as op}from"os";import{randomBytes as ap}from"crypto";import{execFileSync as lp}from"child_process";function _a(t){if(!up.test(t))throw new Error(`Invalid profile name "${t}": must be 1-32 alphanumeric/hyphen chars, no leading/trailing hyphen`);Kn=t}function Zt(){return Kn}function Q(){return Kn?`-${Kn}`:""}function W(){return ya(sp(),".beachviber")}function os(){return ya(W(),`config${Q()}.json`)}function D(){let t=os();if(!is(t))return null;try{return JSON.parse(ep(t,"utf-8"))}catch{return null}}function G(t){let e=W();is(e)||np(e,{recursive:!0,mode:448}),tp(os(),JSON.stringify(t,null,2)+`
|
|
18
|
+
`,{mode:384})}function as(t){let e=os();return is(e)?(cp.warn(`Deleting config file (reason: ${t}): ${e}`),U("config_deleted","session","warn",`Config file deleted (reason: ${t})`,{reason:t}),rp(e),!0):!1}function Tt(){return`dev_${ap(6).toString("hex")}`}function Hn(){let t=D()?.deviceName;if(t)return t;if(op()==="darwin")try{return lp("scutil",["--get","ComputerName"],{encoding:"utf-8"}).trim()}catch{}return ip()}function fe(){return!!D()?.wakePasswordHash}function Xt(){return D()?.wakeSessionDuration??8}function Ae(t){let e=D();e&&(t!==null?e.wakeExpiresAt=t:delete e.wakeExpiresAt,G(e))}var cp,Wn,bt,up,Kn,le=j(()=>{"use strict";ae();Qt();cp=M("config"),Wn="wss://relay.beachviber.com",bt="https://api.beachviber.com",up=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,30}[a-zA-Z0-9])?$/,Kn=null});import{readFileSync as dp,writeFileSync as fp,existsSync as pp,mkdirSync as hp}from"fs";import{join as gp}from"path";import{createHash as mp}from"crypto";function Sa(){if(Je)return Je;try{Je=JSON.parse(dp(wa(),"utf-8"))}catch{Je={}}return Je}function yp(){let t=W();pp(t)||hp(t,{recursive:!0,mode:448}),fp(wa(),JSON.stringify(Je,null,2)+`
|
|
19
|
+
`,{mode:384})}function Ea(t){return mp("sha256").update(t).digest("hex")}function ba(t,e){let n=Ea(t),r=Sa();r[n]=e,Je=r,yp()}function _p(t){let e=Ea(t);return Sa()[e]??null}function ls(t){return _p(Buffer.from(t,"base64"))}var wa,Je,cs=j(()=>{"use strict";le();wa=()=>gp(W(),"image-keys.json"),Je=null});import{readFileSync as kt,writeFileSync as va,mkdirSync as wp,existsSync as Oe,statSync as Ca,readdirSync as Ta,openSync as Sp,readSync as Ep,closeSync as bp}from"fs";import{join as ce,basename as Tp}from"path";import{homedir as Ne}from"os";function en(t){if(!he.test(t))throw new Error(`Invalid session ID format: ${t.slice(0,50)}`)}function Vn(t){let e=Gn(t),n=ce(Ne(),".claude","projects",e,"sessions-index.json"),r=new Map;if(!Oe(n))return r;try{let s=kt(n,"utf-8"),i=JSON.parse(s);if(Array.isArray(i.entries))for(let o of i.entries)r.set(o.sessionId,o)}catch(s){pe.error(`Error reading session index: ${s}`)}return r}function vt(t,e){en(e);let n=Gn(t),r=ce(Ne(),".claude","projects",n,`${e}.jsonl`);try{return Ca(r).mtimeMs}catch{return null}}function Gn(t){return t.replace(/[/\\:]/g,"-")}function us(t,e){en(e);let n=Gn(t),r=ce(Ne(),".claude","projects",n,`${e}.jsonl`);if(!Oe(r))return pe.info(`File not found: ${r}`),[];let s=[],i=[];try{let c=kt(r,"utf-8").split(`
|
|
20
|
+
`);for(let u of c){if(!u.trim())continue;let p;try{p=JSON.parse(u)}catch{continue}let g=p.type;if(g!=="user"&&g!=="assistant")continue;let f=p.message;if(!f)continue;let h=p.timestamp||"",y=f.content;if(g==="user"){let _="";if(typeof y=="string")_=y;else if(Array.isArray(y)){for(let w of y){let x=w;if(x.type==="tool_result"&&x.tool_use_id){let A=i.indexOf(x.tool_use_id);A!==-1&&i.splice(A,1);for(let E=s.length-1;E>=0;E--)if(s[E].role==="assistant"&&s[E].contentBlocks){let T=s[E].contentBlocks.find(k=>k.type==="tool_use"&&k.toolUseId===x.tool_use_id);if(T){let k="";if(typeof x.content=="string")k=x.content;else if(Array.isArray(x.content)){for(let b of x.content)if(b.type==="text")k+=b.text;else if(b.type==="image"){let I=b.source;if(I?.type==="base64"&&I.data&&I.media_type){let We=ls(I.data);We&&(s[E].contentBlocks||(s[E].contentBlocks=[]),s[E].contentBlocks.push({type:"image",url:"",imageKey:We}))}else I?.type==="url"&&I.url&&(s[E].contentBlocks||(s[E].contentBlocks=[]),s[E].contentBlocks.push({type:"image",url:I.url}))}}if(T.name==="Task"){let b=k.match(/agentId:\s*([a-f0-9]+)/);b&&(T.agentId=b[1])}T.result=k.length>2e3?k.slice(0,2e3):k}break}}}_=y.filter(w=>w.type==="text").map(w=>w.text).join("")}_&&s.push({role:"user",content:_,timestamp:h})}else if(g==="assistant"&&Array.isArray(y)){let w=y.filter(T=>T.type==="text").map(T=>T.text).join(""),A=y.filter(T=>T.type==="tool_use").map(T=>{let k=T.name||"unknown",b=T.input,I=k;return b&&(b.command?I=`${k}: ${String(b.command).slice(0,200)}`:b.file_path?I=`${k}: ${String(b.file_path)}`:b.pattern?I=`${k}: ${String(b.pattern).slice(0,200)}`:b.query?I=`${k}: ${String(b.query).slice(0,200)}`:b.url?I=`${k}: ${String(b.url).slice(0,200)}`:b.description&&(I=`${k}: ${String(b.description).slice(0,200)}`)),{tool:I,timestamp:h?new Date(h).getTime():Date.now()}}),E=[];for(let T of y){let k=T;if(k.type==="text")E.push({type:"text",text:k.text});else if(k.type==="image"){let b=k.source;if(b?.type==="base64"&&b.data&&b.media_type){let I=ls(b.data);I&&E.push({type:"image",url:"",imageKey:I})}else b?.type==="url"&&b.url&&E.push({type:"image",url:b.url})}else if(k.type==="tool_use"){let b;k.name==="Task"?i.push(k.id):i.length>0&&(b=i[i.length-1]);let I=k.input;if(I&&JSON.stringify(I).length>1e3){let wn={_truncated:!0};for(let vr of["command","file_path","pattern","query","url","description"])typeof I[vr]=="string"&&(wn[vr]=I[vr]);I=wn}E.push({type:"tool_use",toolUseId:k.id,name:k.name,input:I,...b?{parentToolUseId:b}:{}})}}(w||A.length>0||E.length>0)&&s.push({role:"assistant",content:w,timestamp:h,...A.length>0?{toolUses:A}:{},...E.length>0?{contentBlocks:E}:{}})}}}catch(l){pe.error(`Error reading transcript: ${l}`)}let o=[];for(let l of s){let c=o[o.length-1];c&&c.role==="assistant"&&l.role==="assistant"?(c.content+=l.content,c.timestamp=l.timestamp,l.toolUses?.length&&(c.toolUses=[...c.toolUses||[],...l.toolUses]),l.contentBlocks?.length&&(c.contentBlocks=[...c.contentBlocks||[],...l.contentBlocks])):o.push({...l})}let a=ce(Ne(),".claude","projects",n,e,"subagents");if(Oe(a))for(let l of o){if(l.role!=="assistant"||!l.contentBlocks)continue;let c=[];for(let u of l.contentBlocks){if(c.push(u),u.type!=="tool_use"||u.name!=="Task"||!u.agentId)continue;let p=ce(a,`agent-${u.agentId}.jsonl`);if(Oe(p))try{let g=kt(p,"utf-8");for(let f of g.split(`
|
|
21
|
+
`)){if(!f.trim())continue;let h;try{h=JSON.parse(f)}catch{continue}if(h.type!=="assistant")continue;let y=h.timestamp,_=y?new Date(y).getTime():void 0,w=h.message;if(!(!w||!Array.isArray(w.content)))for(let x of w.content){if(x.type!=="tool_use")continue;let A=x.name||"unknown",T=x.input;if(T&&JSON.stringify(T).length>1e3){let b={_truncated:!0};for(let I of["command","file_path","pattern","query","url","description"])typeof T[I]=="string"&&(b[I]=T[I]);T=b}c.push({type:"tool_use",toolUseId:x.id,name:A,input:T,parentToolUseId:u.toolUseId,..._?{timestamp:_}:{}})}}}catch(g){pe.error(`Error reading subagent transcript ${p}: ${g}`)}}l.contentBlocks=c}return pe.info(`Read ${o.length} messages from ${e}`),o}function ds(){return ce(Ne(),".beachviber",kp)}function Ia(){let t=new Map,e=ds();if(!Oe(e))return t;try{let n=kt(e,"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object")for(let[s,i]of Object.entries(r))i&&typeof i=="object"&&t.set(s,i)}catch(n){pe.error(`Error reading session meta: ${n}`)}return t}function xa(t,e){try{en(t)}catch{return{ok:!1,error:"Invalid session ID"}}if(typeof e!="string"||e.length===0)return{ok:!1,error:"Title must be a non-empty string"};let n=e.trim();if(n.length===0)return{ok:!1,error:"Title must not be blank"};if(n.length>ka)return{ok:!1,error:`Title must be at most ${ka} characters`};if(vp.test(n)===!1)return{ok:!1,error:"Title contains invalid characters"};try{let r=ds(),s=ce(Ne(),".beachviber"),i={};if(Oe(r))try{let o=JSON.parse(kt(r,"utf-8"));i=o&&typeof o=="object"&&!Array.isArray(o)?o:{}}catch{i={}}else wp(s,{recursive:!0});return i[t]||(i[t]={}),i[t].title=n,va(r,JSON.stringify(i,null,2)+`
|
|
22
|
+
`,{encoding:"utf-8"}),pe.info(`Renamed session ${t.slice(0,20)} to "${n.slice(0,50)}" in session-meta.json`),{ok:!0}}catch(r){return pe.error(`Failed to rename session ${t.slice(0,20)}: ${r}`),{ok:!1,error:"Failed to write session metadata"}}}function Ra(t){try{en(t)}catch{return}let e=ds();if(Oe(e))try{let n=JSON.parse(kt(e,"utf-8"));n&&typeof n=="object"&&!Array.isArray(n)&&t in n&&(delete n[t],va(e,JSON.stringify(n,null,2)+`
|
|
23
|
+
`,{encoding:"utf-8"}),pe.info(`Removed session-meta entry for ${t.slice(0,20)}`))}catch(n){pe.error(`Failed to delete session-meta for ${t.slice(0,20)}: ${n}`)}}function Pa(t){try{let e=Sp(t,"r"),n=Ca(t).size,r=Math.min(n,262144),s=Buffer.alloc(r),i=Ep(e,s,0,r,0);bp(e);let o=s.toString("utf-8",0,i);for(let a of o.split(`
|
|
24
|
+
`))if(a)try{let l=JSON.parse(a);if(l.type!=="user")continue;let c=l.message;if(!c)continue;let u="";if(typeof c.content=="string"?u=c.content:Array.isArray(c.content)&&(u=c.content.filter(p=>p.type==="text").map(p=>p.text).join("")),u=u.trim(),u)return u.length>120?u.slice(0,120)+"\u2026":u}catch{}}catch{}}function Aa(t,e){try{en(e)}catch{return}let n=Gn(t),r=ce(Ne(),".claude","projects",n,`${e}.jsonl`);return Pa(r)}function fs(t){let e=ce(Ne(),".claude","projects");if(!Oe(e))return[];let n=[],r=new Set,s;try{s=Ta(e,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name)}catch{return[]}for(let i of s){let o=ce(e,i),a=ss(o);if(!a)continue;let l=Tp(a),c=Vn(a),u;try{u=Ta(o).filter(p=>p.endsWith(".jsonl"))}catch{continue}for(let p of u){let g=p.replace(".jsonl","");if(!he.test(g)||t.has(g)||r.has(g))continue;r.add(g);let f=c.get(g),h,y,_,w;f&&(h=f.summary,w=f.firstPrompt,y=f.messageCount,_=f.modified?new Date(f.modified).getTime():void 0),_||(_=vt(a,g)??void 0),w||(w=Pa(ce(o,p))),h||(h=w),n.push({claudeSessionId:g,projectPath:a,projectName:l,summary:h,firstPrompt:w,messageCount:y,lastMessageTime:_})}}return n.sort((i,o)=>(o.lastMessageTime??0)-(i.lastMessageTime??0)),n}var pe,kp,ka,vp,ps=j(()=>{"use strict";Ct();jn();ae();cs();pe=M("transcripts");kp="session-meta.json";ka=200,vp=/^[\p{L}\p{N}\p{Zs}\-_.,:;!?'"()[\]{}&@#%+=/~`<>*^|$]+$/u});import hs from"net";import Cp from"crypto";import gs from"fs";import Ip from"path";function Jn(){let t=Q();return zn?`\\\\.\\pipe\\beachviber-control-${Cp.createHash("sha256").update(W()).digest("hex").slice(0,8)}${t}`:Ip.join(W(),`control${t}.sock`)}function Oa(t){if(Te)return;if(ge=Jn(),!zn){let n=W();gs.mkdirSync(n,{recursive:!0,mode:448});try{gs.unlinkSync(ge)}catch{}}let e=new Set;if(Te=hs.createServer({allowHalfOpen:!0},n=>{if(e.size>=Pp){n.destroy();return}e.add(n),n.on("close",()=>e.delete(n));let r="",s=0,i=!1;n.setTimeout(Rp,()=>{n.destroy()});let o=async()=>{if(i)return;i=!0;let a;try{a=JSON.parse(r)}catch{n.write(JSON.stringify({ok:!1,message:"Invalid JSON"})+`
|
|
24
25
|
`),n.end();return}if(!a.type||typeof a.type!="string"){n.write(JSON.stringify({ok:!1,message:"Missing command type"})+`
|
|
25
26
|
`),n.end();return}try{let l=await t(a);n.write(JSON.stringify(l)+`
|
|
26
|
-
`)}catch(l){
|
|
27
|
-
`)}n.end()};n.on("data",a=>{if(s+=a.length,s>
|
|
27
|
+
`)}catch(l){Yn.error(`Command handler error: ${l}`),n.write(JSON.stringify({ok:!1,message:"Internal error"})+`
|
|
28
|
+
`)}n.end()};n.on("data",a=>{if(s+=a.length,s>xp){n.write(JSON.stringify({ok:!1,message:"Request too large"})+`
|
|
28
29
|
`),n.end();return}r+=a.toString(),r.includes(`
|
|
29
|
-
`)&&(r=r.trim(),o())}),n.on("end",()=>{r=r.trim(),o()}),n.on("error",()=>{})}),
|
|
30
|
-
`)}),o="",a=setTimeout(()=>{i.destroy(),s(new Error("IPC timeout"))},e);i.on("data",l=>{o+=l.toString()}),i.on("end",()=>{clearTimeout(a);try{r(JSON.parse(o.trim()))}catch{s(new Error("Invalid response from control server"))}}),i.on("error",l=>{clearTimeout(a),s(l)})})}function
|
|
31
|
-
`)||a.length>200)){if(o+a.length>
|
|
32
|
-
`),R.info(`control_response: requestId=${n} approved=${r}`)}resolveApproval(e,n,r,s){let i=this.pendingApprovals.get(e);if(!i)return!1;let o=this.sessions.get(i.sessionId);if(!o)return!1;o.lastActivityAt=Date.now();let a=this.approvalTimeouts.get(e);a&&(clearTimeout(a),this.approvalTimeouts.delete(e));let l;return n&&r&&i.tool==="AskUserQuestion"&&(l={...i.toolInput,answers:r}),this.writeControlResponse(o,e,n,i.toolUseId,i.toolInput,n?void 0:"Denied by user",l),R.info(`Approval resolved: approvalId=${e} approved=${n}`),o.resolvedApprovals.push({approvalId:e,tool:i.tool,description:i.description,command:i.command,approved:n,timestamp:Date.now()}),this.persistSessions(),this.pendingApprovals.delete(e),s&&n&&(this.addStickyApproval(i.sessionId,i.tool,s.durationMinutes),this.autoResolvePendingForTool(i.sessionId,i.tool)),!0}hasStickyApproval(e,n){let r=`${e}:${n}`,s=this.stickyApprovals.get(r);return s?Date.now()>=s.expiresAt?(this.stickyApprovals.delete(r),!1):!0:!1}addStickyApproval(e,n,r){let s=Math.max(1,Math.min(r||0,480)),i=`${e}:${n}`;this.stickyApprovals.set(i,{tool:n,sessionId:e,expiresAt:Date.now()+s*6e4}),R.info(`Sticky approval added: ${i} for ${s}m`),this.stickyCleanupTimer||(this.stickyCleanupTimer=setInterval(()=>this.pruneSticky(),6e4),this.stickyCleanupTimer.unref())}pruneSticky(){let e=Date.now();for(let[n,r]of this.stickyApprovals)e>=r.expiresAt&&(this.stickyApprovals.delete(n),R.info(`Sticky approval expired: ${n}`));this.stickyApprovals.size===0&&this.stickyCleanupTimer&&(clearInterval(this.stickyCleanupTimer),this.stickyCleanupTimer=null)}autoResolvePendingForTool(e,n){let r=[];for(let[s,i]of this.pendingApprovals)i.sessionId===e&&i.tool===n&&r.push(s);for(let s of r)R.info(`Auto-resolving pending approval ${s} via sticky rule (${n})`),this.resolveApproval(s,!0)}clearStickyApprovals(e){let n=0;for(let[r]of this.stickyApprovals)r.startsWith(`${e}:`)&&(this.stickyApprovals.delete(r),n++);n>0&&R.info(`Cleared ${n} sticky approval(s) for session ${e}`),this.stickyApprovals.size===0&&this.stickyCleanupTimer&&(clearInterval(this.stickyCleanupTimer),this.stickyCleanupTimer=null)}startIdleReaper(){this.idleReaperTimer||(this.idleReaperTimer=setInterval(()=>this.reapIdleSessions(),
|
|
33
|
-
`));let i=Le(r,`settings-${e.id}.json`);
|
|
34
|
-
`);f=y.pop()||"";for(let _ of y)if(_.trim()){
|
|
35
|
-
`;i.stdin?.write(o,a=>{a&&(R.error(`Failed to write to stdin for session ${e.id}: ${a.message}`),e.busy=!1,e.currentMessageId=void 0,r({type:"stream_end",sessionId:e.id,timestamp:Date.now(),payload:{messageId:s,exitCode:1}}),this.drainQueue(e))})}};
|
|
30
|
+
`)&&(r=r.trim(),o())}),n.on("end",()=>{r=r.trim(),o()}),n.on("error",()=>{})}),zn)Te.on("error",n=>{if(n.code!=="EADDRINUSE")throw n;let r=hs.createConnection(ge,()=>{r.destroy(),Yn.error("Another instance is already running (pipe in use).")});r.on("error",()=>{Yn.info("Stale pipe detected, retrying..."),setTimeout(()=>Te?.listen(ge),500)})}),Te.listen(ge);else{let n=process.umask(127);Te.listen(ge,()=>{process.umask(n)})}Yn.info(`Control server listening on ${ge}`)}function ms(t,e=5e3){let n=Jn();return new Promise((r,s)=>{let i=hs.createConnection(n,()=>{i.write(JSON.stringify(t)+`
|
|
31
|
+
`)}),o="",a=setTimeout(()=>{i.destroy(),s(new Error("IPC timeout"))},e);i.on("data",l=>{o+=l.toString()}),i.on("end",()=>{clearTimeout(a);try{r(JSON.parse(o.trim()))}catch{s(new Error("Invalid response from control server"))}}),i.on("error",l=>{clearTimeout(a),s(l)})})}function Na(){if(Te&&(Te.close(),Te=null),!zn&&ge)try{gs.unlinkSync(ge)}catch{}ge=""}var Yn,xp,Rp,Pp,zn,Te,ge,ys=j(()=>{"use strict";le();ae();Yn=M("ipc-control"),xp=64*1024,Rp=5e3,Pp=10,zn=process.platform==="win32",Te=null,ge=""});import{spawn as La}from"child_process";import{readFileSync as Fa,writeFileSync as _s,mkdirSync as Ba,existsSync as ws}from"fs";import{join as Le}from"path";import{tmpdir as Ma}from"os";import{randomUUID as Ap}from"crypto";function Es(t){return t=t.replace(/[\r\n]+/g," "),/[\s"&|<>()^!%]/.test(t)?'"'+t.replace(/%/g,"%%").replace(/"/g,'""').replace(/\^/g,"^^").replace(/!/g,"^!")+'"':t}function Np(t){let e=t;for(let n of Op)n.lastIndex=0,e=e.replace(n,(r,...s)=>r.includes("=")&&s.length>=2?`${s[0]}=<redacted>`:r.startsWith("Bearer")?"Bearer <redacted>":`${r.slice(0,Math.min(6,r.length))}...<redacted>`);return e}function Da(){return Le(W(),`sessions${Q()}.json`)}function Dp(t,e,n,r){let s=t.type;if(s==="system"&&t.subtype==="init"){e.claudeSessionId=t.session_id,t.model&&(e.model=t.model),R.info(`Claude session ID captured: ${e.claudeSessionId} model=${e.model||"unknown"} for session ${e.id}`);return}if(s==="system"&&t.subtype==="compact_boundary"){let i=e.currentMessageId||n,o=t.compact_metadata;R.info(`Compaction complete: trigger=${o?.trigger} pre_tokens=${o?.pre_tokens} session=${e.id}`),r({type:"stream_meta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:i,status:"compacted"}});return}if(s==="system"&&(t.subtype==="informational"||t.subtype==="status")){let i=t.content??t.message??"";if(i&&i.toLowerCase().includes("compact")){let o=e.currentMessageId||n;R.info(`Compaction starting: session=${e.id}`),r({type:"stream_meta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:o,status:"compacting"}});return}R.info(`system event subtype=${t.subtype} content=${String(t.content??t.message??"").slice(0,200)} session=${e.id}`)}if(s==="assistant"){let i=t.message;if(i&&Array.isArray(i.content)){let o=i.content.some(a=>a.type==="thinking");o&&!e.isThinking?(e.isThinking=!0,r({type:"stream_meta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:n,status:"thinking"}})):!o&&e.isThinking&&(e.isThinking=!1);for(let a of i.content){if(a.type==="text"&&a.text){let l=te.get(n)??0;te.set(n,l+1),r({type:"stream_delta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:n,delta:a.text,deltaType:"text",blockIndex:l}})}if(a.type==="image"){let l=te.get(n)??0;te.set(n,l+1);let c=a.source;if(c?.type==="base64"&&c.data&&c.media_type){let u=Buffer.from(c.data,"base64");Ua(r,e.id,n,l,u,c.media_type)}else c?.type==="url"&&c.url&&r({type:"stream_delta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:n,delta:c.url,deltaType:"image",blockIndex:l}})}if(a.type==="tool_use"){let l=te.get(n)??0;te.set(n,l+1);let c=a.input,u=a.name;c&&(c.command?u=`Bash: ${c.command}`:c.file_path?u=`${a.name}: ${c.file_path}`:c.pattern?u=`${a.name}: ${c.pattern}`:c.query?u=`${a.name}: ${c.query}`:c.url?u=`${a.name}: ${c.url}`:c.description&&(u=`${a.name}: ${c.description}`));let p=c;if(c){let y=JSON.stringify(c);if(y.length>1e3){let _={_truncated:!0,_preview:y.slice(0,1e3)};for(let w of["command","file_path","pattern","query","url","description"])typeof c[w]=="string"&&(_[w]=c[w]);p=_}}let g=Qe.get(n)||[],f;a.name==="Task"?(g.push(a.id),Qe.set(n,g)):g.length>0&&(f=g[g.length-1]);let h={messageId:n,delta:u,deltaType:"tool_use",blockIndex:l,toolUseId:a.id,toolInput:p};f&&(h.parentToolUseId=f),r({type:"stream_delta",sessionId:e.id,timestamp:Date.now(),payload:h})}}}return}if(s==="user"){let i=t.message;if(i&&Array.isArray(i.content)){for(let o of i.content)if(o.type==="tool_result"&&o.content){let a=Qe.get(n)||[],l=o.tool_use_id,c=a.indexOf(l),u;c!==-1?(a.splice(c,1),a.length===0&&Qe.delete(n)):a.length>0&&(u=a[a.length-1]);let p="";if(typeof o.content=="string")p=o.content;else if(Array.isArray(o.content)){for(let f of o.content)if(f.type==="text")p+=f.text;else if(f.type==="image"){let h=f.source;if(h?.type==="base64"&&h.data&&h.media_type){let y=te.get(n)??0;te.set(n,y+1);let _=Buffer.from(h.data,"base64");Ua(r,e.id,n,y,_,h.media_type)}else if(h?.type==="url"&&h.url){let y=te.get(n)??0;te.set(n,y+1),r({type:"stream_delta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:n,delta:h.url,deltaType:"image",blockIndex:y}})}}}else p=String(o.content);let g={messageId:n,delta:p.slice(0,2e3),deltaType:"tool_result",toolUseId:l};u&&(g.parentToolUseId=u),r({type:"stream_delta",sessionId:e.id,timestamp:Date.now(),payload:g})}}return}}function $p(t){try{return JSON.parse(Fa(t,"utf-8"))}catch{return null}}function Fp(t){let e=[],n=process.env.HOME||process.env.USERPROFILE||"",r=[Le(n,".claude","settings.json"),Le(t,".claude","settings.json"),Le(t,".claude","settings.local.json")];for(let a of r){let c=$p(a)?.permissions;Array.isArray(c?.allow)&&e.push(...c.allow)}let s=new Set,i=[],o=0;for(let a of e)if(!s.has(a)&&!(a.includes(`
|
|
32
|
+
`)||a.length>200)){if(o+a.length>Up)break;s.add(a),i.push(a),o+=a.length}return i}function ja(t,e){let n=Qn.get(t);n&&(clearTimeout(n.timer),Qn.delete(t),n.resolve(e))}function qp(t,e,n,r){let s=`img_${Ap()}`;return new Promise((i,o)=>{let a=setTimeout(()=>{Qn.delete(s),o(new Error("Image upload request timed out"))},jp);Qn.set(s,{resolve:i,reject:o,timer:a}),t({type:"image_upload_request",sessionId:e,timestamp:Date.now(),payload:{requestId:s,contentType:n,fileName:r}})})}async function Kp(t,e,n){let r=await fetch(t,{method:"PUT",headers:{"Content-Type":n},body:new Uint8Array(e),signal:AbortSignal.timeout(3e4)});if(!r.ok)throw new Error(`S3 upload failed: ${r.status}`)}async function Ua(t,e,n,r,s,i){let o=i.split("/")[1]||"png",a=`claude-image-${Date.now()}.${o}`;try{let{putUrl:l,getUrl:c,key:u}=await qp(t,e,i,a);await Kp(l,s,i),ba(s,u),t({type:"stream_delta",sessionId:e,timestamp:Date.now(),payload:{messageId:n,delta:c,deltaType:"image",blockIndex:r}})}catch(l){R.error(`Image upload failed: ${l}`),t({type:"stream_delta",sessionId:e,timestamp:Date.now(),payload:{messageId:n,delta:"",deltaType:"image",blockIndex:r}})}}function qa(){return Zn=new Ss,Zn}function ke(){if(!Zn)throw new Error("SessionManager not initialized \u2014 call initSessionManager first");return Zn}var R,It,tn,Op,he,$a,Lp,Bp,Mp,Ss,Up,te,Qe,jp,Qn,Zn,Ct=j(()=>{"use strict";dt();ps();le();ys();ae();cs();R=M("sessions"),It=M("prompt"),tn=M("claude");Op=[/\b(sk-[a-zA-Z0-9]{20,})/g,/\b(bv_[a-f0-9]{20,})/g,/\b(ghp_[a-zA-Z0-9]{20,})/g,/\b(npm_[a-zA-Z0-9]{20,})/g,/\b([A-Z_]*(?:SECRET|TOKEN|KEY|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=(\S+)/gi,/Bearer\s+\S+/gi];he=/^[a-zA-Z0-9_-]{1,128}$/,$a=5,Lp=3e5,Bp=10*6e4,Mp=6e4,Ss=class{sessions=new Map;pendingApprovals=new Map;approvalTimeouts=new Map;lastPhoneReplyTo=null;phoneSendFn=null;stickyApprovals=new Map;stickyCleanupTimer=null;idleReaperTimer=null;constructor(){this.loadPersistedSessions()}setPhoneSendFn(e){this.phoneSendFn=e}loadPersistedSessions(){try{let e=Da();if(!ws(e))return;let n=Fa(e,"utf-8"),r=JSON.parse(n),s=0;for(let i of r){if(i.claudeSessionId)try{if(vt(i.projectPath,i.claudeSessionId)===null){s++;continue}}catch{s++;continue}let o={id:i.id,projectId:i.projectId,projectPath:i.projectPath,projectName:i.projectName,claudeSessionId:i.claudeSessionId,resolvedApprovals:i.resolvedApprovals||[],busy:!1,promptQueue:[],lastActivityAt:Date.now()};this.sessions.set(o.id,o)}s>0&&(R.info(`Pruned ${s} orphan session(s) with no matching transcript`),this.persistSessions()),R.info(`Loaded ${this.sessions.size} persisted sessions`)}catch(e){R.error(`Failed to load persisted sessions: ${e}`)}}persistSessions(){try{let e=W();ws(e)||Ba(e,{recursive:!0});let n=Array.from(this.sessions.values()).map(r=>({id:r.id,projectId:r.projectId,projectPath:r.projectPath,projectName:r.projectName,claudeSessionId:r.claudeSessionId,resolvedApprovals:r.resolvedApprovals.length>0?r.resolvedApprovals:void 0}));_s(Da(),JSON.stringify(n,null,2),{encoding:"utf-8",mode:384})}catch(e){R.error(`Failed to persist sessions: ${e}`)}}getAllSessions(){return Array.from(this.sessions.values())}createSession(e,n){let r={id:e,projectId:n.id,projectPath:n.path,projectName:n.name,resolvedApprovals:[],busy:!1,promptQueue:[],lastActivityAt:Date.now()};return this.sessions.set(e,r),this.persistSessions(),R.info(`Created session ${e} for project ${n.name}`),r}getSession(e){return this.sessions.get(e)}stopProcess(e,n){let r=this.sessions.get(e);if(!r)return!1;let s=r.busy,i=r.currentMessageId;r.promptQueue.length=0,r.busy=!1,r.currentMessageId=void 0;for(let[a,l]of this.pendingApprovals)if(l.sessionId===e){this.pendingApprovals.delete(a);let c=this.approvalTimeouts.get(a);c&&(clearTimeout(c),this.approvalTimeouts.delete(a))}if(!r.process)return!1;n&&s&&i&&n({type:"stream_end",sessionId:r.id,timestamp:Date.now(),payload:{messageId:i,exitCode:null}});let o=r.process;return r.process=void 0,o.kill(),!0}endSession(e){let n=this.sessions.get(e);if(!n)return!1;n.process&&n.process.kill(),n.promptQueue.length=0;for(let[r,s]of this.pendingApprovals)if(s.sessionId===e){this.pendingApprovals.delete(r);let i=this.approvalTimeouts.get(r);i&&(clearTimeout(i),this.approvalTimeouts.delete(r))}return this.clearStickyApprovals(e),this.sessions.delete(e),this.persistSessions(),R.info(`Ended session ${e}`),!0}getActiveSessions(){return Array.from(this.sessions.keys())}handleControlRequest(e,n,r){let s=e.request_id,i=e.request;if(i?.subtype!=="can_use_tool"){R.warn(`Unknown control_request subtype: ${i?.subtype}`),this.writeControlResponse(n,s,!1,"",void 0,`Unsupported request: ${i?.subtype}`);return}let o=i.tool_name,a=i.input||{},l=i.tool_use_id||"",c=o,u;o==="ExitPlanMode"?c="Plan complete \u2014 review and approve to proceed":o==="Bash"&&a.command?(c=`Run: ${a.command}`,u=a.command):a.file_path?c=`${o}: ${a.file_path}`:a.pattern?c=`${o}: ${a.pattern}`:a.query?c=`${o}: ${a.query}`:a.url?c=`${o}: ${a.url}`:a.description&&(c=`${o}: ${a.description}`);let p={approvalId:s,sessionId:n.id,tool:o,toolInput:a,toolUseId:l,description:c,command:u};if(o==="AskUserQuestion"&&Array.isArray(a.questions)&&(p.questions=a.questions),o!=="AskUserQuestion"&&o!=="ExitPlanMode"&&this.hasStickyApproval(n.id,o)){R.info(`Sticky auto-approve: requestId=${s} tool=${o} session=${n.id}`),this.writeControlResponse(n,s,!0,l,a),n.resolvedApprovals.push({approvalId:s,tool:o,description:c,command:u,approved:!0,timestamp:Date.now()}),this.persistSessions();return}this.pendingApprovals.set(s,p),R.info(`control_request: requestId=${s} tool=${o} session=${n.id}`);let g={approvalId:s,tool:o,description:c};if(u&&(g.command=u),p.questions&&(g.questions=p.questions),o==="ExitPlanMode"&&(typeof a.plan=="string"&&(g.plan=a.plan.slice(0,1e5)),Array.isArray(a.allowedPrompts)&&(g.allowedPrompts=a.allowedPrompts)),n.currentMessageId){let w=Qe.get(n.currentMessageId);w&&w.length>0&&(g.parentToolUseId=w[w.length-1])}let f=this.phoneSendFn||r,h=this.lastPhoneReplyTo;if(!f({type:"tool_approval_request",sessionId:n.id,timestamp:Date.now(),payload:g,...h?{_replyTo:h}:{}})){R.warn(`Phone not connected -- auto-denying requestId=${s}`),this.writeControlResponse(n,s,!1,l,a,"Phone not connected"),this.pendingApprovals.delete(s);return}let _=setTimeout(()=>{this.pendingApprovals.has(s)&&(R.warn(`Approval timeout for requestId=${s}`),this.resolveApproval(s,!1))},Lp);this.approvalTimeouts.set(s,_)}writeControlResponse(e,n,r,s,i,o,a){if(!e.process?.stdin?.writable){R.error(`Cannot write control_response for ${n} -- stdin not writable`);return}let l={behavior:r?"allow":"deny"};r&&(l.updatedInput=a||i||{},l.toolUseID=s),o&&(l.message=o);let c={type:"control_response",response:{subtype:"success",request_id:n,response:l}};e.process.stdin.write(JSON.stringify(c)+`
|
|
33
|
+
`),R.info(`control_response: requestId=${n} approved=${r}`)}resolveApproval(e,n,r,s){let i=this.pendingApprovals.get(e);if(!i)return!1;let o=this.sessions.get(i.sessionId);if(!o)return!1;o.lastActivityAt=Date.now();let a=this.approvalTimeouts.get(e);a&&(clearTimeout(a),this.approvalTimeouts.delete(e));let l;return n&&r&&i.tool==="AskUserQuestion"&&(l={...i.toolInput,answers:r}),this.writeControlResponse(o,e,n,i.toolUseId,i.toolInput,n?void 0:"Denied by user",l),R.info(`Approval resolved: approvalId=${e} approved=${n}`),o.resolvedApprovals.push({approvalId:e,tool:i.tool,description:i.description,command:i.command,approved:n,timestamp:Date.now()}),this.persistSessions(),this.pendingApprovals.delete(e),s&&n&&(this.addStickyApproval(i.sessionId,i.tool,s.durationMinutes),this.autoResolvePendingForTool(i.sessionId,i.tool)),!0}hasStickyApproval(e,n){let r=`${e}:${n}`,s=this.stickyApprovals.get(r);return s?Date.now()>=s.expiresAt?(this.stickyApprovals.delete(r),!1):!0:!1}addStickyApproval(e,n,r){let s=Math.max(1,Math.min(r||0,480)),i=`${e}:${n}`;this.stickyApprovals.set(i,{tool:n,sessionId:e,expiresAt:Date.now()+s*6e4}),R.info(`Sticky approval added: ${i} for ${s}m`),this.stickyCleanupTimer||(this.stickyCleanupTimer=setInterval(()=>this.pruneSticky(),6e4),this.stickyCleanupTimer.unref())}pruneSticky(){let e=Date.now();for(let[n,r]of this.stickyApprovals)e>=r.expiresAt&&(this.stickyApprovals.delete(n),R.info(`Sticky approval expired: ${n}`));this.stickyApprovals.size===0&&this.stickyCleanupTimer&&(clearInterval(this.stickyCleanupTimer),this.stickyCleanupTimer=null)}autoResolvePendingForTool(e,n){let r=[];for(let[s,i]of this.pendingApprovals)i.sessionId===e&&i.tool===n&&r.push(s);for(let s of r)R.info(`Auto-resolving pending approval ${s} via sticky rule (${n})`),this.resolveApproval(s,!0)}clearStickyApprovals(e){let n=0;for(let[r]of this.stickyApprovals)r.startsWith(`${e}:`)&&(this.stickyApprovals.delete(r),n++);n>0&&R.info(`Cleared ${n} sticky approval(s) for session ${e}`),this.stickyApprovals.size===0&&this.stickyCleanupTimer&&(clearInterval(this.stickyCleanupTimer),this.stickyCleanupTimer=null)}startIdleReaper(){this.idleReaperTimer||(this.idleReaperTimer=setInterval(()=>this.reapIdleSessions(),Mp),this.idleReaperTimer.unref())}reapIdleSessions(){let e=Date.now(),n=0;for(let r of this.sessions.values()){if(!r.process||r.process.exitCode!==null||(n++,r.busy)||this.hasPendingApprovalsForSession(r.id)||r.promptQueue.length>0)continue;let s=e-(r.lastActivityAt||0);if(s>=Bp){R.info(`Reaping idle process for session ${r.id} (idle ${Math.round(s/1e3)}s)`);let i=r.process;r.process=void 0,i.kill()}}n===0&&this.idleReaperTimer&&(clearInterval(this.idleReaperTimer),this.idleReaperTimer=null)}hasPendingApprovalsForSession(e){for(let n of this.pendingApprovals.values())if(n.sessionId===e)return!0;return!1}getPendingApprovals(){return Array.from(this.pendingApprovals.values())}getResolvedApprovals(e){return this.sessions.get(e)?.resolvedApprovals||[]}notifyCompactStart(e){let n=this.sessions.get(e);if(!n?.currentMessageId)return;R.info(`Compaction starting (via IPC hook): session=${e}`),this.buildLiveSend()({type:"stream_meta",sessionId:e,timestamp:Date.now(),payload:{messageId:n.currentMessageId,status:"compacting"}})}buildLiveSend(){return e=>{let n=this.phoneSendFn,r=this.lastPhoneReplyTo;return n&&r?n({...e,_replyTo:r}):this.phoneSendFn?.(e)??!1}}_testRouteClaudeEvent(e,n,r){this.routeClaudeEvent(e,n,r)}ensureProcess(e,n){if(e.process&&e.process.exitCode===null)return e.process;let r=Le(Ma(),"beachviber-hooks");Ba(r,{recursive:!0});let s=Le(r,"compact-hook.js");ws(s)||_s(s,["const net = require('net');","const c = net.createConnection(process.env.BEACHVIBER_CONTROL_SOCKET, () => {"," c.write(JSON.stringify({ type: 'compact_start', sessionId: process.env.BEACHVIBER_SESSION_ID }) + '\\n');"," c.end();","});","c.on('error', () => {});"].join(`
|
|
34
|
+
`));let i=Le(r,`settings-${e.id}.json`);_s(i,JSON.stringify({hooks:{PreCompact:[{hooks:[{type:"command",command:`node "${s}"`}]}]}}));let o=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--permission-mode","default","--settings",i],a=Fp(e.projectPath);a.length>0&&o.push("--allowedTools",...a),e.claudeSessionId&&(o.push("--resume",e.claudeSessionId),It.info(`Resuming Claude session ${e.claudeSessionId}`));let l=Le(Ma(),"beachviber-images");o.push("--add-dir",l);let c={...process.env};delete c.CLAUDECODE,c.BEACHVIBER_CONTROL_SOCKET=Jn(),c.BEACHVIBER_SESSION_ID=e.id;let u=o.map(h=>h.length>100?`"<${h.length} chars>"`:h);It.info(`Spawning: claude ${u.join(" ")}`),It.info(`CWD: ${e.projectPath}`);let p=process.platform==="win32"?La("claude "+o.map(Es).join(" "),[],{cwd:e.projectPath,env:c,stdio:["pipe","pipe","pipe"],shell:!0}):La("claude",o,{cwd:e.projectPath,env:c,stdio:["pipe","pipe","pipe"]});if(e.process=p,this.startIdleReaper(),It.info(`Claude process spawned (PID: ${p.pid})`),!p.pid)return It.error("Claude process failed to spawn (PID undefined)"),e.busy=!1,e.process=void 0,n({type:"error",sessionId:e.id,timestamp:Date.now(),payload:{code:"SPAWN_FAILED",message:"Claude process failed to start \u2014 try again or restart the desktop agent"}}),this.drainQueue(e),p;n({type:"process_spawned",sessionId:e.id,timestamp:Date.now(),payload:{hasProcess:!0}});let g=h=>{let y=this.phoneSendFn,_=this.lastPhoneReplyTo;return y&&_?y({...h,_replyTo:_}):n(h)},f="";return p.stdout?.on("data",h=>{f+=h.toString();let y=f.split(`
|
|
35
|
+
`);f=y.pop()||"";for(let _ of y)if(_.trim()){tn.debug(`raw stdout: ${_.slice(0,300)}`);try{let w=JSON.parse(_);this.routeClaudeEvent(w,e,g)}catch{tn.warn(`non-JSON stdout line: ${_.slice(0,200)}`)}}}),p.stdout?.on("end",()=>{tn.info(`stdout ended for session ${e.id}`)}),p.stderr?.on("data",h=>{let y=h.toString().trim();y&&tn.info(`stderr: ${Np(y)}`)}),p.on("close",h=>{if(f.trim())try{let w=JSON.parse(f);this.routeClaudeEvent(w,e,g)}catch{}if(e.process!==void 0&&e.process!==p){R.info(`Stale close event for ${e.id} (new process already running), skipping cleanup`);return}e.currentMessageId&&(te.delete(e.currentMessageId),Qe.delete(e.currentMessageId));let _=e.busy;e.busy=!1,e.process=void 0,R.info(`Process closed for ${e.id}, code=${h} claudeSessionId=${e.claudeSessionId||"NOT SET"}`),this.persistSessions(),g({type:"process_ended",sessionId:e.id,timestamp:Date.now(),payload:{exitCode:h}}),_&&e.currentMessageId&&(g({type:"stream_end",sessionId:e.id,timestamp:Date.now(),payload:{messageId:e.currentMessageId,exitCode:h}}),e.currentMessageId=void 0);for(let[w,x]of this.pendingApprovals)if(x.sessionId===e.id){this.pendingApprovals.delete(w);let A=this.approvalTimeouts.get(w);A&&(clearTimeout(A),this.approvalTimeouts.delete(w))}R.info(`Claude process exited with code ${h} for session ${e.id}`),this.drainQueue(e)}),p.on("error",h=>{e.busy=!1,e.process=void 0,g({type:"error",sessionId:e.id,timestamp:Date.now(),payload:{code:"CLAUDE_ERROR",message:`Failed to start Claude: ${h.message}`}}),this.drainQueue(e)}),p}routeClaudeEvent(e,n,r){let s=e.type,i=e.subtype;if(tn.info(`event type=${s} subtype=${i||""} session=${n.id}`),s==="control_request"){this.handleControlRequest(e,n,r);return}if(s==="result"){n.lastActivityAt=Date.now();let a=n.currentMessageId;if(a){te.delete(a),Qe.delete(a),n.busy=!1;let l=e.usage,c={messageId:a};e.duration_ms!=null&&(c.durationMs=e.duration_ms),e.duration_api_ms!=null&&(c.durationApiMs=e.duration_api_ms),e.total_cost_usd!=null&&(c.totalCostUsd=e.total_cost_usd),e.num_turns!=null&&(c.numTurns=e.num_turns),l&&(c.usage={inputTokens:l.input_tokens,outputTokens:l.output_tokens}),Object.keys(c).length>1&&r({type:"stream_meta",sessionId:n.id,timestamp:Date.now(),payload:c}),n.isThinking=!1,r({type:"stream_end",sessionId:n.id,timestamp:Date.now(),payload:{messageId:a,exitCode:0}}),console.log(m.green(" Response sent")),n.currentMessageId=void 0}this.drainQueue(n);return}let o=n.currentMessageId||`msg_${Date.now()}`;Dp(e,n,o,r)}drainQueue(e){let n=e.promptQueue.shift();n&&(R.info(`Draining queue for session ${e.id} (${e.promptQueue.length} remaining)`),this.runPrompt(e,n.message,n.send))}runPrompt(e,n,r){if(e.lastActivityAt=Date.now(),e.busy){if(e.promptQueue.length>=$a){r({type:"error",sessionId:e.id,timestamp:Date.now(),payload:{code:"QUEUE_FULL",message:`Prompt queue is full (max ${$a})`}});return}e.promptQueue.push({message:n,send:r}),R.info(`Queued prompt for session ${e.id} (queue size: ${e.promptQueue.length})`),r({type:"prompt_queued",sessionId:e.id,timestamp:Date.now(),payload:{position:e.promptQueue.length}});return}e.busy=!0;let s=`msg_${Date.now()}`;e.currentMessageId=s,It.info(`Session ${e.id} | Project: ${e.projectName} | Message: <${n.length} chars>`),r({type:"stream_start",sessionId:e.id,timestamp:Date.now(),payload:{messageId:s}}),e.streamStartedAt=Date.now(),e.model&&r({type:"stream_meta",sessionId:e.id,timestamp:Date.now(),payload:{messageId:s,model:e.model}});let i=this.ensureProcess(e,r),o=JSON.stringify({type:"user",message:{role:"user",content:n}})+`
|
|
36
|
+
`;i.stdin?.write(o,a=>{a&&(R.error(`Failed to write to stdin for session ${e.id}: ${a.message}`),e.busy=!1,e.currentMessageId=void 0,r({type:"stream_end",sessionId:e.id,timestamp:Date.now(),payload:{messageId:s,exitCode:1}}),this.drainQueue(e))})}};Up=6e3;te=new Map,Qe=new Map,jp=15e3,Qn=new Map;Zn=null});import{execFileSync as Be,spawnSync as Wp}from"child_process";import{readFileSync as Ka,writeFileSync as Wa,mkdirSync as Ha,existsSync as Xn,unlinkSync as Va}from"fs";import{join as ks}from"path";import{platform as vs}from"os";function tr(){return ks(W(),"secrets")}function bs(t,e){let n=`${t}_${e}`.replace(/[^a-zA-Z0-9_-]/g,"_");return ks(tr(),`${n}.dpapi`)}function Ts(t,e){let n=`${t}_${e}`.replace(/[^a-zA-Z0-9_-]/g,"_");return ks(tr(),`${n}.key`)}function nr(){return xt!==void 0||(xt=zp.find(t=>t.isAvailable())??null,xt?er.info(`Using ${xt.name} for secret storage`):er.warn("No OS secret store available -- secret key will not be persisted")),xt}function Ga(t,e){let n=nr();if(!n)return!1;try{return n.store(Cs,t,e),!0}catch(r){return er.warn(`Failed to store secret: ${r}`),!1}}function Ya(t){let e=nr();if(!e)return null;try{return e.load(Cs,t)}catch(n){return er.warn(`Failed to load secret: ${n}`),null}}function rr(t){let e=nr();if(e)try{e.remove(Cs,t)}catch{}}function za(){return nr()?.name??null}var er,Hp,Vp,Gp,Yp,Cs,zp,xt,Is=j(()=>{"use strict";le();ae();er=M("secrets"),Hp={name:"macOS Keychain",isAvailable(){return vs()==="darwin"},store(t,e,n){Be("security",["add-generic-password","-s",t,"-a",e,"-w",n,"-U"],{stdio:"ignore"})},load(t,e){try{return Be("security",["find-generic-password","-s",t,"-a",e,"-w"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}},remove(t,e){try{Be("security",["delete-generic-password","-s",t,"-a",e],{stdio:"ignore"})}catch{}}};Vp={name:"Windows DPAPI",isAvailable(){return vs()==="win32"},store(t,e,n){let r=tr();Xn(r)||Ha(r,{recursive:!0});let i=Be("powershell.exe",["-NoProfile","-NonInteractive","-Command",`
|
|
36
37
|
Add-Type -AssemblyName System.Security
|
|
37
38
|
$secret = [Console]::In.ReadToEnd()
|
|
38
39
|
$bytes = [System.Text.Encoding]::UTF8.GetBytes($secret)
|
|
39
40
|
$enc = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
|
|
40
41
|
[Convert]::ToBase64String($enc)
|
|
41
|
-
`],{input:n,encoding:"utf-8",windowsHide:!0}).trim();
|
|
42
|
+
`],{input:n,encoding:"utf-8",windowsHide:!0}).trim();Wa(bs(t,e),i)},load(t,e){let n=bs(t,e);if(!Xn(n))return null;try{let r=Ka(n,"utf-8").trim();return Be("powershell.exe",["-NoProfile","-NonInteractive","-Command",`
|
|
42
43
|
Add-Type -AssemblyName System.Security
|
|
43
44
|
$b64 = [Console]::In.ReadToEnd()
|
|
44
45
|
$enc = [Convert]::FromBase64String($b64)
|
|
45
46
|
$dec = [System.Security.Cryptography.ProtectedData]::Unprotect($enc, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
|
|
46
47
|
[System.Text.Encoding]::UTF8.GetString($dec)
|
|
47
|
-
`],{input:r,encoding:"utf-8",windowsHide:!0}).trim()||null}catch{return null}},remove(t,e){let n=_s(t,e);try{Ma(n)}catch{}}},vp={name:"Linux Secret Service",isAvailable(){return Es()!=="linux"||!process.env.DBUS_SESSION_BUS_ADDRESS?!1:!bp("secret-tool",["--help"],{stdio:"ignore",timeout:3e3}).error},store(t,e,n){Be("secret-tool",["store","--label",`${t}:${e}`,"service",t,"account",e],{input:n,stdio:["pipe","ignore","ignore"]})},load(t,e){try{return Be("secret-tool",["lookup","service",t,"account",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}},remove(t,e){try{Be("secret-tool",["clear","service",t,"account",e],{stdio:"ignore"})}catch{}}};Cp={name:"file storage",isAvailable(){return!0},store(t,e,n){let r=Xn();Qn(r)||Ba(r,{recursive:!0,mode:448}),La(ws(t,e),n,{mode:384})},load(t,e){let n=ws(t,e);if(!Qn(n))return null;try{return Na(n,"utf-8").trim()||null}catch{return null}},remove(t,e){try{Ma(ws(t,e))}catch{}}},bs="beachviber",Ip=[Tp,kp,vp,Cp]});import ke from"crypto";import{deflateRawSync as xp,inflateRawSync as Rp}from"node:zlib";function en(){let{publicKey:t,privateKey:e}=ke.generateKeyPairSync("x25519");return{publicKey:t,secretKey:e}}function ge(t){let e=t.export({format:"jwk"});return Buffer.from(e.x,"base64url")}function tn(t){let e=t.toString("base64url");return ke.createPublicKey({format:"jwk",key:{kty:"OKP",crv:"X25519",x:e}})}function rr(t,e){return ke.diffieHellman({publicKey:t,privateKey:e})}function Fa(t,e,n){let r=ke.randomBytes(12),s=ke.createCipheriv("aes-256-gcm",e,r),i=Buffer.from(JSON.stringify(t)),o=n&&i.length>=Pp,a=o?xp(i):i;if(o){let p=(i.length/a.length).toFixed(1);nr.debug(`deflate: ${i.length}B \u2192 ${a.length}B (${p}x)`)}let l=Buffer.concat([s.update(a),s.final()]),c=s.getAuthTag(),u=Buffer.concat([l,c]);return{nonce:r.toString("base64"),ciphertext:u.toString("base64"),...o?{compressed:!0}:{}}}function ja(t,e){let n=Buffer.from(t.nonce,"base64"),r=Buffer.from(t.ciphertext,"base64"),s=r.subarray(0,r.length-16),i=r.subarray(r.length-16),o=ke.createDecipheriv("aes-256-gcm",e,n);o.setAuthTag(i);let a=Buffer.concat([o.update(s),o.final()]);if(t.compressed){let l=a.length;a=Rp(a),nr.info(`inflate: ${l}B \u2192 ${a.length}B`)}return JSON.parse(a.toString("utf-8"))}function qa(t,e){let n=t.subarray(0,12),r=t.subarray(t.length-16),s=t.subarray(12,t.length-16),i=ke.createDecipheriv("aes-256-gcm",e,n);return i.setAuthTag(r),Buffer.concat([i.update(s),i.final()])}function Y(t){return Buffer.from(t).toString("base64")}function It(t){return Buffer.from(t,"base64")}function Ka(){return`default${Q()}`}function Wa(){let t=D();if(!t||!t.publicKey)return null;let e=$a(Ka());return e?{publicKey:t.publicKey,secretKey:e,peerPublicKey:t.peerPublicKey}:null}function xt(t){let e=D();Da(Ka(),t.secretKey)||nr.warn("OS secret store unavailable -- secret key will not be persisted");let n=!!e?.deviceToken;nr.info(`saveKeys: writing config (deviceToken ${n?`preserved, len=${e.deviceToken.length}`:"absent"})`),G({...e,deviceId:e?.deviceId||"",deviceToken:e?.deviceToken,publicKey:t.publicKey,peerPublicKey:t.peerPublicKey??e?.peerPublicKey})}function ks(t,e){return new Promise((n,r)=>{ke.pbkdf2(t,e,1e5,32,"sha512",(s,i)=>{s?r(s):n(i.toString("hex"))})})}function sr(t,e){let n=Buffer.from(t,"hex"),r=Buffer.from(e,"hex");return n.length!==r.length?!1:ke.timingSafeEqual(n,r)}var nr,Pp,Je,Rt=K(()=>{"use strict";pe();Ts();oe();nr=M("crypto"),Pp=1024;Je=new Set(["verify_code","verify_code_ack","hello","hello_ack","prompt","stream_start","stream_delta","stream_end","stream_meta","session_create","session_created","session_end","rename_session","projects_request","projects_response","tool_approval_request","tool_approval_response","sessions_request","sessions_response","session_history_request","session_history_response","sticky_approvals_clear","prompt_ack","error","wake","wake_ack","sleep_notify","force_sleep","session_delete","session_delete_response","process_stop","process_stop_ack","session_status_request","session_status_response","process_spawned","process_ended"])});import{mkdirSync as Ap,existsSync as Ha,readdirSync as Op,statSync as Np,unlinkSync as Lp,writeFileSync as Bp}from"fs";import{join as vs}from"path";import{homedir as Mp}from"os";import{randomUUID as Dp}from"crypto";function Fp(){Ha(Pt)||Ap(Pt,{recursive:!0,mode:448})}function jp(t){try{let n=new URL(t).pathname.match(/\.(\w+)(?:\?|$)/);if(n&&$p.has(n[1].toLowerCase()))return n[1].toLowerCase()}catch{}return"png"}async function Va(t,e){let n=new URL(t);if(n.protocol!=="https:")throw new Error(`Image download blocked: only HTTPS URLs are allowed (got ${n.protocol})`);if(!qp.test(n.hostname))throw new Error(`Image download blocked: hostname "${n.hostname}" is not an allowed S3 host`);Fp();let r=e?.encrypted&&e.contentType?Kp[e.contentType]??"png":jp(t),s=`${Dp()}.${r}`,i=vs(Pt,s),o=await fetch(t,{signal:AbortSignal.timeout(Wp)});if(!o.ok)throw new Error(`Failed to download image: ${o.status} ${o.statusText}`);if(!e?.encrypted){let f=(o.headers.get("content-type")||"").split(";")[0].trim().toLowerCase();if(f&&!Up.has(f))throw new Error(`Image download blocked: unexpected Content-Type "${f}"`)}let a=Number(o.headers.get("content-length")||0);if(a>ir)throw new Error(`Image too large: ${a} bytes (max ${ir})`);let l=[],c=0,u=o.body?.getReader();if(!u)throw new Error("No response body");for(;;){let{done:f,value:h}=await u.read();if(f)break;if(c+=h.byteLength,c>ir)throw u.cancel(),new Error(`Image too large: exceeded ${ir} bytes during download`);l.push(Buffer.from(h))}let p=Buffer.concat(l),g=e?.encrypted&&e.sharedSecret?qa(Buffer.from(p),e.sharedSecret):p;return Bp(i,g,{mode:384}),i}function Cs(){if(!Ha(Pt))return;let t=Date.now(),e=3600*1e3;try{for(let n of Op(Pt)){let r=vs(Pt,n);try{let s=Np(r);t-s.mtimeMs>e&&Lp(r)}catch{}}}catch{}}var Pt,$p,Up,qp,Kp,ir,Wp,Is=K(()=>{"use strict";Rt();Pt=vs(Mp(),".beachviber","images"),$p=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","heic"]),Up=new Set(["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","image/heic"]);qp=/^beachviber-uploads-\w+\.s3[\w.-]*\.amazonaws\.com$/,Kp={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/heic":"heic"},ir=50*1024*1024,Wp=3e4});var or={};Lu(or,{buildHistoryBatches:()=>Za,computeReconnectDelay:()=>Ls,handleMessage:()=>Os,printBanner:()=>Me,sendPostPairingData:()=>Ns,transitionToSleep:()=>As});import za from"crypto";import{createDeflateRaw as Hp,constants as Vp}from"node:zlib";import{spawn as Ga}from"child_process";function Gp(t){return t?za.createHash("sha256").update(t).digest("hex").slice(0,12):"null"}function Me(t,e){let n=Math.max(...t.map(s=>s.length)),r=n+2;console.log(),console.log(e(` \u2554${"\u2550".repeat(r)}\u2557`));for(let s of t)console.log(e(` \u2551 ${s.padEnd(n)} \u2551`));console.log(e(` \u255A${"\u2550".repeat(r)}\u255D`))}function Ja(t){return de.test(t)}function zp(t){return Qp(),nn.has(t)}function Jp(t){nn.set(t,Date.now()+Yp)}function Qp(){if(nn.size<100)return;let t=Date.now();for(let[e,n]of nn)n<t&&nn.delete(e)}function Qa(){let t=Hp(),e=0;return t.on("data",n=>{e+=n.length}),{write(n){t.write(n)},flush(){return new Promise(n=>{t.flush(Vp.Z_SYNC_FLUSH,()=>n(e))})},destroy(){t.destroy()}}}async function Za(t,e){if(t.length===0)return[];if(!e){let s=[],i=[],o=2;for(let a of t){let l=Buffer.byteLength(JSON.stringify(a)),c=i.length===0?l:l+1;o+c>Ps&&i.length>0?(s.push(i),i=[a],o=2+l):(i.push(a),o+=c)}return i.length>0&&s.push(i),s}let n=[],r=0;for(;r<t.length;){let s=Qa(),i=0,o=0,a=!1;for(s.write("[");r+o<t.length;){let l=o,c=Math.min(o+Xp,t.length-r);for(let p=l;p<c;p++){let g=p===0?"":",";s.write(g+JSON.stringify(t[r+p]))}if(o=c,await s.flush()>Ps){a=!0;break}i=o}if(s.destroy(),!a)n.push(t.slice(r,r+o)),r+=o;else if(i>0)n.push(t.slice(r,r+i)),r+=i;else{let l=await eh(t,r,o);n.push(t.slice(r,r+l)),r+=l}}return n}async function eh(t,e,n){let r=Qa();r.write("[");let s=0;for(let i=0;i<n;i++){let o=i===0?"":",";if(r.write(o+JSON.stringify(t[e+i])),await r.flush()>Ps)break;s=i+1}return r.destroy(),Math.max(s,1)}function Xa(t,e){let n=e.map(r=>({id:r.id,name:r.name,path:r.path,git:r.git,sessionCount:r.sessionCount}));v.info(`Sending ${n.length} projects to app:`);for(let r of n)v.info(` id=${r.id} name="${r.name}" path="${r.path}" branch=${r.git.branch} sessions=${r.sessionCount}`);if(n.length===0){t({type:"projects_response",sessionId:null,timestamp:Date.now(),payload:{projects:[],done:!0}});return}for(let r=0;r<n.length;r+=xs){let s=n.slice(r,r+xs),i=r+xs>=n.length;t({type:"projects_response",sessionId:null,timestamp:Date.now(),payload:{projects:s,done:i}})}}function Ya(t,e){let r=jn(t).get(e);return r?.modified?new Date(r.modified).getTime():Et(t,e)??void 0}async function th(t){let e=await wt();return Xa(t.sendFn,e),console.log(m.dim(` Synced ${e.length} project${e.length!==1?"s":""} with app`)),e}async function nh(t){let e=t.payload.projectId,n=aa(t.projects,e);if(!n){t.sendFn({type:"error",sessionId:t.sessionId,timestamp:Date.now(),payload:{code:"PROJECT_NOT_FOUND",message:`Project ${e} is not registered on this device`}});return}let r=t.sessionMgr.createSession(t.sessionId,n),s=t.payload.claudeSessionId;if(s&&de.test(s)){let l=t.sessionMgr.getAllSessions().find(c=>c.claudeSessionId===s&&c.id!==r.id);if(l){t.sessionMgr.endSession(r.id),console.log(m.dim(` CLI session ${s.slice(0,8)}... already adopted as ${l.id}`));let u=(await Un(n.path))?.git||n.git,p=Ya(n.path,s);t.sendFn({type:"session_created",sessionId:l.id,timestamp:Date.now(),payload:{projectId:n.id,projectName:n.name,cwd:n.path,git:u,lastMessageTime:p,claudeSessionId:s}});return}r.claudeSessionId=s,t.sessionMgr.persistSessions(),console.log(m.green(` Adopted CLI session: ${s.slice(0,8)}...`))}console.log(m.green(` Session started: ${n.name}/${n.git.branch}`));let o=(await Un(n.path))?.git||n.git,a=r.claudeSessionId?Ya(n.path,r.claudeSessionId):void 0;t.sendFn({type:"session_created",sessionId:r.id,timestamp:Date.now(),payload:{projectId:n.id,projectName:n.name,cwd:n.path,git:o,lastMessageTime:a,...r.claudeSessionId?{claudeSessionId:r.claudeSessionId}:{}}})}function rh(t){t.sessionId&&(t.sessionMgr.endSession(t.sessionId),console.log(m.dim(" Session ended")))}async function sh(t){let e=t.payload?.sessionId;if(!e){v.warn("session_delete: missing sessionId");return}let n=t.sessionMgr.getSession(e),r=n?.claudeSessionId,s=n?.projectPath;if(n&&t.sessionMgr.endSession(e),r&&s)try{await ih(r,s)}catch(i){v.error(`session_delete: failed to clear Claude session ${r.slice(0,20)}: ${i}`)}r&&ha(r),v.info(`session_delete: deleted session ${e.slice(0,20)}`),t.sendFn({type:"session_delete_response",sessionId:null,timestamp:Date.now(),payload:{sessionId:e}})}function ih(t,e){return new Promise((n,r)=>{let s=["-p","/clear","--resume",t],i={...process.env};delete i.CLAUDECODE,v.info(`Clearing Claude session: claude ${s.join(" ")}`);let o=process.platform==="win32"?Ga("claude "+s.map(ys).join(" "),[],{cwd:e,env:i,stdio:["ignore","pipe","pipe"],shell:!0}):Ga("claude",s,{cwd:e,env:i,stdio:["ignore","pipe","pipe"]}),a=setTimeout(()=>{o.kill(),r(new Error("claude /clear timed out"))},15e3);o.on("close",l=>{clearTimeout(a),l===0?(v.info(`Claude session ${t.slice(0,20)} cleared`),n()):r(new Error(`claude /clear exited with code ${l}`))}),o.on("error",l=>{clearTimeout(a),r(l)})})}function oh(t){let e=t.payload,n=e?.claudeSessionId,r=e?.title;if(!n||!r){v.warn("rename_session: missing claudeSessionId or title");return}let s=pa(n,r);s.ok?v.info(`rename_session: renamed ${n.slice(0,20)} to "${r.slice(0,50)}"`):v.warn(`rename_session: failed -- ${s.error}`)}async function ah(t){if(!t.sessionId){t.sendFn({type:"error",sessionId:null,timestamp:Date.now(),payload:{code:"SESSION_NOT_FOUND",message:"No sessionId provided"}});return}let e=t.sessionMgr.getSession(t.sessionId);if(!e){t.sendFn({type:"error",sessionId:t.sessionId,timestamp:Date.now(),payload:{code:"SESSION_NOT_FOUND",message:`Session ${t.sessionId} doesn't exist`}});return}let n=t.payload._msgId;n&&t.sendFn({type:"prompt_ack",sessionId:t.sessionId,timestamp:Date.now(),payload:{_msgId:n}});let r=t.payload.message;if(!r)return;let s=t.payload.imageGetUrl;if(s)try{let i=t.payload.imageEncrypted,o=t.payload.imageContentType,a=await Va(s,i?{encrypted:!0,contentType:o,sharedSecret:d.sharedSecret??void 0}:void 0);r=`[The user attached an image at: ${a}]
|
|
48
|
+
`],{input:r,encoding:"utf-8",windowsHide:!0}).trim()||null}catch{return null}},remove(t,e){let n=bs(t,e);try{Va(n)}catch{}}},Gp={name:"Linux Secret Service",isAvailable(){return vs()!=="linux"||!process.env.DBUS_SESSION_BUS_ADDRESS?!1:!Wp("secret-tool",["--help"],{stdio:"ignore",timeout:3e3}).error},store(t,e,n){Be("secret-tool",["store","--label",`${t}:${e}`,"service",t,"account",e],{input:n,stdio:["pipe","ignore","ignore"]})},load(t,e){try{return Be("secret-tool",["lookup","service",t,"account",e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}},remove(t,e){try{Be("secret-tool",["clear","service",t,"account",e],{stdio:"ignore"})}catch{}}};Yp={name:"file storage",isAvailable(){return!0},store(t,e,n){let r=tr();Xn(r)||Ha(r,{recursive:!0,mode:448}),Wa(Ts(t,e),n,{mode:384})},load(t,e){let n=Ts(t,e);if(!Xn(n))return null;try{return Ka(n,"utf-8").trim()||null}catch{return null}},remove(t,e){try{Va(Ts(t,e))}catch{}}},Cs="beachviber",zp=[Hp,Vp,Gp,Yp]});import ve from"crypto";import{deflateRawSync as Jp,inflateRawSync as Qp}from"node:zlib";function nn(){let{publicKey:t,privateKey:e}=ve.generateKeyPairSync("x25519");return{publicKey:t,secretKey:e}}function me(t){let e=t.export({format:"jwk"});return Buffer.from(e.x,"base64url")}function rn(t){let e=t.toString("base64url");return ve.createPublicKey({format:"jwk",key:{kty:"OKP",crv:"X25519",x:e}})}function ir(t,e){return ve.diffieHellman({publicKey:t,privateKey:e})}function Ja(t,e,n){let r=ve.randomBytes(12),s=ve.createCipheriv("aes-256-gcm",e,r),i=Buffer.from(JSON.stringify(t)),o=n&&i.length>=Zp,a=o?Jp(i):i;if(o){let p=(i.length/a.length).toFixed(1);sr.debug(`deflate: ${i.length}B \u2192 ${a.length}B (${p}x)`)}let l=Buffer.concat([s.update(a),s.final()]),c=s.getAuthTag(),u=Buffer.concat([l,c]);return{nonce:r.toString("base64"),ciphertext:u.toString("base64"),...o?{compressed:!0}:{}}}function Qa(t,e){let n=Buffer.from(t.nonce,"base64"),r=Buffer.from(t.ciphertext,"base64"),s=r.subarray(0,r.length-16),i=r.subarray(r.length-16),o=ve.createDecipheriv("aes-256-gcm",e,n);o.setAuthTag(i);let a=Buffer.concat([o.update(s),o.final()]);if(t.compressed){let l=a.length;a=Qp(a),sr.info(`inflate: ${l}B \u2192 ${a.length}B`)}return JSON.parse(a.toString("utf-8"))}function Za(t,e){let n=t.subarray(0,12),r=t.subarray(t.length-16),s=t.subarray(12,t.length-16),i=ve.createDecipheriv("aes-256-gcm",e,n);return i.setAuthTag(r),Buffer.concat([i.update(s),i.final()])}function Y(t){return Buffer.from(t).toString("base64")}function Rt(t){return Buffer.from(t,"base64")}function Xa(){return`default${Q()}`}function el(){let t=D();if(!t||!t.publicKey)return null;let e=Ya(Xa());return e?{publicKey:t.publicKey,secretKey:e,peerPublicKey:t.peerPublicKey}:null}function Pt(t){let e=D();Ga(Xa(),t.secretKey)||sr.warn("OS secret store unavailable -- secret key will not be persisted");let n=!!e?.deviceToken;sr.info(`saveKeys: writing config (deviceToken ${n?`preserved, len=${e.deviceToken.length}`:"absent"})`),G({...e,deviceId:e?.deviceId||"",deviceToken:e?.deviceToken,publicKey:t.publicKey,peerPublicKey:t.peerPublicKey??e?.peerPublicKey})}function xs(t,e){return new Promise((n,r)=>{ve.pbkdf2(t,e,1e5,32,"sha512",(s,i)=>{s?r(s):n(i.toString("hex"))})})}function or(t,e){let n=Buffer.from(t,"hex"),r=Buffer.from(e,"hex");return n.length!==r.length?!1:ve.timingSafeEqual(n,r)}var sr,Zp,Ze,At=j(()=>{"use strict";le();Is();ae();sr=M("crypto"),Zp=1024;Ze=new Set(["verify_code","verify_code_ack","hello","hello_ack","prompt","stream_start","stream_delta","stream_end","stream_meta","session_create","session_created","session_end","rename_session","projects_request","projects_response","tool_approval_request","tool_approval_response","sessions_request","sessions_response","session_history_request","session_history_response","sticky_approvals_clear","prompt_ack","error","wake","wake_ack","sleep_notify","force_sleep","session_delete","session_delete_response","process_stop","process_stop_ack","session_status_request","session_status_response","process_spawned","process_ended","image_upload_request","image_upload_url"])});import{mkdirSync as Xp,existsSync as tl,readdirSync as eh,statSync as th,unlinkSync as nh,writeFileSync as rh}from"fs";import{join as Rs}from"path";import{homedir as sh}from"os";import{randomUUID as ih}from"crypto";function lh(){tl(Ot)||Xp(Ot,{recursive:!0,mode:448})}function ch(t){try{let n=new URL(t).pathname.match(/\.(\w+)(?:\?|$)/);if(n&&oh.has(n[1].toLowerCase()))return n[1].toLowerCase()}catch{}return"png"}async function nl(t,e){let n=new URL(t);if(n.protocol!=="https:")throw new Error(`Image download blocked: only HTTPS URLs are allowed (got ${n.protocol})`);if(!uh.test(n.hostname))throw new Error(`Image download blocked: hostname "${n.hostname}" is not an allowed S3 host`);lh();let r=e?.encrypted&&e.contentType?dh[e.contentType]??"png":ch(t),s=`${ih()}.${r}`,i=Rs(Ot,s),o=await fetch(t,{signal:AbortSignal.timeout(fh)});if(!o.ok)throw new Error(`Failed to download image: ${o.status} ${o.statusText}`);if(!e?.encrypted){let f=(o.headers.get("content-type")||"").split(";")[0].trim().toLowerCase();if(f&&!ah.has(f))throw new Error(`Image download blocked: unexpected Content-Type "${f}"`)}let a=Number(o.headers.get("content-length")||0);if(a>ar)throw new Error(`Image too large: ${a} bytes (max ${ar})`);let l=[],c=0,u=o.body?.getReader();if(!u)throw new Error("No response body");for(;;){let{done:f,value:h}=await u.read();if(f)break;if(c+=h.byteLength,c>ar)throw u.cancel(),new Error(`Image too large: exceeded ${ar} bytes during download`);l.push(Buffer.from(h))}let p=Buffer.concat(l),g=e?.encrypted&&e.sharedSecret?Za(Buffer.from(p),e.sharedSecret):p;return rh(i,g,{mode:384}),i}function Ps(){if(!tl(Ot))return;let t=Date.now(),e=3600*1e3;try{for(let n of eh(Ot)){let r=Rs(Ot,n);try{let s=th(r);t-s.mtimeMs>e&&nh(r)}catch{}}}catch{}}var Ot,oh,ah,uh,dh,ar,fh,As=j(()=>{"use strict";At();Ot=Rs(sh(),".beachviber","images"),oh=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","heic"]),ah=new Set(["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","image/heic"]);uh=/^beachviber-uploads-\w+\.s3[\w.-]*\.amazonaws\.com$/,dh={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/heic":"heic"},ar=50*1024*1024,fh=3e4});var lr={};Wu(lr,{buildHistoryBatches:()=>ll,computeReconnectDelay:()=>$s,handleMessage:()=>Ms,printBanner:()=>Me,sendPostPairingData:()=>Ds,transitionToSleep:()=>Bs});import il from"crypto";import{createDeflateRaw as ph,constants as hh}from"node:zlib";import{spawn as rl}from"child_process";function gh(t){return t?il.createHash("sha256").update(t).digest("hex").slice(0,12):"null"}function Me(t,e){let n=Math.max(...t.map(s=>s.length)),r=n+2;console.log(),console.log(e(` \u2554${"\u2550".repeat(r)}\u2557`));for(let s of t)console.log(e(` \u2551 ${s.padEnd(n)} \u2551`));console.log(e(` \u255A${"\u2550".repeat(r)}\u255D`))}function ol(t){return he.test(t)}function yh(t){return wh(),sn.has(t)}function _h(t){sn.set(t,Date.now()+mh)}function wh(){if(sn.size<100)return;let t=Date.now();for(let[e,n]of sn)n<t&&sn.delete(e)}function al(){let t=ph(),e=0;return t.on("data",n=>{e+=n.length}),{write(n){t.write(n)},flush(){return new Promise(n=>{t.flush(hh.Z_SYNC_FLUSH,()=>n(e))})},destroy(){t.destroy()}}}async function ll(t,e){if(t.length===0)return[];if(!e){let s=[],i=[],o=2;for(let a of t){let l=Buffer.byteLength(JSON.stringify(a)),c=i.length===0?l:l+1;o+c>Ls&&i.length>0?(s.push(i),i=[a],o=2+l):(i.push(a),o+=c)}return i.length>0&&s.push(i),s}let n=[],r=0;for(;r<t.length;){let s=al(),i=0,o=0,a=!1;for(s.write("[");r+o<t.length;){let l=o,c=Math.min(o+Eh,t.length-r);for(let p=l;p<c;p++){let g=p===0?"":",";s.write(g+JSON.stringify(t[r+p]))}if(o=c,await s.flush()>Ls){a=!0;break}i=o}if(s.destroy(),!a)n.push(t.slice(r,r+o)),r+=o;else if(i>0)n.push(t.slice(r,r+i)),r+=i;else{let l=await bh(t,r,o);n.push(t.slice(r,r+l)),r+=l}}return n}async function bh(t,e,n){let r=al();r.write("[");let s=0;for(let i=0;i<n;i++){let o=i===0?"":",";if(r.write(o+JSON.stringify(t[e+i])),await r.flush()>Ls)break;s=i+1}return r.destroy(),Math.max(s,1)}function cl(t,e){let n=e.map(r=>({id:r.id,name:r.name,path:r.path,git:r.git,sessionCount:r.sessionCount}));v.info(`Sending ${n.length} projects to app:`);for(let r of n)v.info(` id=${r.id} name="${r.name}" path="${r.path}" branch=${r.git.branch} sessions=${r.sessionCount}`);if(n.length===0){t({type:"projects_response",sessionId:null,timestamp:Date.now(),payload:{projects:[],done:!0}});return}for(let r=0;r<n.length;r+=Os){let s=n.slice(r,r+Os),i=r+Os>=n.length;t({type:"projects_response",sessionId:null,timestamp:Date.now(),payload:{projects:s,done:i}})}}function sl(t,e){let r=Vn(t).get(e);return r?.modified?new Date(r.modified).getTime():vt(t,e)??void 0}async function Th(t){let e=await Et();return cl(t.sendFn,e),console.log(m.dim(` Synced ${e.length} project${e.length!==1?"s":""} with app`)),e}async function kh(t){let e=t.payload.projectId,n=da(t.projects,e);if(!n){t.sendFn({type:"error",sessionId:t.sessionId,timestamp:Date.now(),payload:{code:"PROJECT_NOT_FOUND",message:`Project ${e} is not registered on this device`}});return}let r=t.sessionMgr.createSession(t.sessionId,n),s=t.payload.claudeSessionId;if(s&&he.test(s)){let l=t.sessionMgr.getAllSessions().find(c=>c.claudeSessionId===s&&c.id!==r.id);if(l){t.sessionMgr.endSession(r.id),console.log(m.dim(` CLI session ${s.slice(0,8)}... already adopted as ${l.id}`));let u=(await Fn(n.path))?.git||n.git,p=sl(n.path,s);t.sendFn({type:"session_created",sessionId:l.id,timestamp:Date.now(),payload:{projectId:n.id,projectName:n.name,cwd:n.path,git:u,lastMessageTime:p,claudeSessionId:s}});return}r.claudeSessionId=s,t.sessionMgr.persistSessions(),console.log(m.green(` Adopted CLI session: ${s.slice(0,8)}...`))}console.log(m.green(` Session started: ${n.name}/${n.git.branch}`));let o=(await Fn(n.path))?.git||n.git,a=r.claudeSessionId?sl(n.path,r.claudeSessionId):void 0;t.sendFn({type:"session_created",sessionId:r.id,timestamp:Date.now(),payload:{projectId:n.id,projectName:n.name,cwd:n.path,git:o,lastMessageTime:a,...r.claudeSessionId?{claudeSessionId:r.claudeSessionId}:{}}})}function vh(t){t.sessionId&&(t.sessionMgr.endSession(t.sessionId),console.log(m.dim(" Session ended")))}async function Ch(t){let e=t.payload?.sessionId;if(!e){v.warn("session_delete: missing sessionId");return}let n=t.sessionMgr.getSession(e),r=n?.claudeSessionId,s=n?.projectPath;if(n&&t.sessionMgr.endSession(e),r&&s)try{await Ih(r,s)}catch(i){v.error(`session_delete: failed to clear Claude session ${r.slice(0,20)}: ${i}`)}r&&Ra(r),v.info(`session_delete: deleted session ${e.slice(0,20)}`),t.sendFn({type:"session_delete_response",sessionId:null,timestamp:Date.now(),payload:{sessionId:e}})}function Ih(t,e){return new Promise((n,r)=>{let s=["-p","/clear","--resume",t],i={...process.env};delete i.CLAUDECODE,v.info(`Clearing Claude session: claude ${s.join(" ")}`);let o=process.platform==="win32"?rl("claude "+s.map(Es).join(" "),[],{cwd:e,env:i,stdio:["ignore","pipe","pipe"],shell:!0}):rl("claude",s,{cwd:e,env:i,stdio:["ignore","pipe","pipe"]}),a=setTimeout(()=>{o.kill(),r(new Error("claude /clear timed out"))},15e3);o.on("close",l=>{clearTimeout(a),l===0?(v.info(`Claude session ${t.slice(0,20)} cleared`),n()):r(new Error(`claude /clear exited with code ${l}`))}),o.on("error",l=>{clearTimeout(a),r(l)})})}function xh(t){let e=t.payload,n=e?.claudeSessionId,r=e?.title;if(!n||!r){v.warn("rename_session: missing claudeSessionId or title");return}let s=xa(n,r);s.ok?v.info(`rename_session: renamed ${n.slice(0,20)} to "${r.slice(0,50)}"`):v.warn(`rename_session: failed -- ${s.error}`)}async function Rh(t){if(!t.sessionId){t.sendFn({type:"error",sessionId:null,timestamp:Date.now(),payload:{code:"SESSION_NOT_FOUND",message:"No sessionId provided"}});return}let e=t.sessionMgr.getSession(t.sessionId);if(!e){t.sendFn({type:"error",sessionId:t.sessionId,timestamp:Date.now(),payload:{code:"SESSION_NOT_FOUND",message:`Session ${t.sessionId} doesn't exist`}});return}let n=t.payload._msgId;n&&t.sendFn({type:"prompt_ack",sessionId:t.sessionId,timestamp:Date.now(),payload:{_msgId:n}});let r=t.payload.message;if(!r)return;let s=t.payload.imageGetUrl;if(s)try{let i=t.payload.imageEncrypted,o=t.payload.imageContentType,a=await nl(s,i?{encrypted:!0,contentType:o,sharedSecret:d.sharedSecret??void 0}:void 0);r=`[The user attached an image at: ${a}]
|
|
48
49
|
|
|
49
|
-
${r}`,console.log(m.dim(` Image downloaded: ${a}${i?" (decrypted)":""}`))}catch(i){let o=i instanceof Error&&i.cause?` cause: ${i.cause}`:"";console.error(m.red(` Failed to download image: ${i}${o}`))}console.log(m.blue(" Prompt received \u2014 Claude is working...")),t.sessionMgr.runPrompt(e,r,t.sendFn)}function
|
|
50
|
+
${r}`,console.log(m.dim(` Image downloaded: ${a}${i?" (decrypted)":""}`))}catch(i){let o=i instanceof Error&&i.cause?` cause: ${i.cause}`:"";console.error(m.red(` Failed to download image: ${i}${o}`))}console.log(m.blue(" Prompt received \u2014 Claude is working...")),t.sessionMgr.runPrompt(e,r,t.sendFn)}function Ph(t){let e=t.payload.approvalId,n=t.payload.approved,r=t.payload.answers,s=t.payload.sticky;v.info(`tool_approval_response received: approvalId=${e} approved=${n} hasAnswers=${!!r} sticky=${s?`${s.tool}/${s.durationMinutes}m`:"none"}`),e?t.sessionMgr.resolveApproval(e,n,r,s):v.warn("tool_approval_response missing approvalId -- ignored")}function Ah(t){t.sessionId?(t.sessionMgr.clearStickyApprovals(t.sessionId),v.info(`sticky_approvals_clear: cleared rules for session ${t.sessionId}`)):v.warn("sticky_approvals_clear: no sessionId provided -- ignored")}function Oh(t){if(t.sessionId){let e=t.sessionMgr.stopProcess(t.sessionId,t.sendFn);v.info(`process_stop: session ${t.sessionId} \u2014 ${e?"process killed":"no process running"}`),U("process_stop","session","info",`Process stop: session ${t.sessionId} \u2014 ${e?"killed":"no process"}`,{sessionId:t.sessionId,stopped:e}),t.sendFn({type:"process_stop_ack",sessionId:t.sessionId,timestamp:Date.now(),payload:{stopped:e,hasProcess:!1}})}else v.warn("process_stop: no sessionId provided -- ignored")}function Nh(t){if(!t.sessionId){v.warn("session_status_request: no sessionId provided -- ignored");return}let e=t.sessionMgr.getSession(t.sessionId);t.sendFn({type:"session_status_response",sessionId:t.sessionId,timestamp:Date.now(),payload:{hasProcess:!!e?.process,busy:!!e?.busy,queuePosition:e?.promptQueue.length??0}})}function ul(t){let e=new Set,n=t.sessionMgr.getAllSessions().filter(f=>!f.claudeSessionId||e.has(f.claudeSessionId)?!1:(e.add(f.claudeSessionId),!0)),r=new Set(n.map(f=>f.claudeSessionId).filter(Boolean)),s=Ia(),i=new Map;for(let f of n)i.has(f.projectPath)||i.set(f.projectPath,Vn(f.projectPath));let o=n.map(f=>{let h=f.claudeSessionId?i.get(f.projectPath)?.get(f.claudeSessionId):void 0,y=f.claudeSessionId?s.get(f.claudeSessionId):void 0,_=h?.messageCount??(f.claudeSessionId?us(f.projectPath,f.claudeSessionId).length:0);return{id:f.id,projectId:f.projectId,projectName:f.projectName,projectPath:f.projectPath,claudeSessionId:f.claudeSessionId,summary:y?.title??h?.summary,firstPrompt:h?.firstPrompt||(f.claudeSessionId?Aa(f.projectPath,f.claudeSessionId):void 0),messageCount:_,lastMessageTime:h?.modified?new Date(h.modified).getTime():f.claudeSessionId?vt(f.projectPath,f.claudeSessionId)??void 0:void 0,type:"beachviber",...f.busy?{busy:!0}:{},hasProcess:!!f.process}}),l=fs(r).map(f=>{let h=s.get(f.claudeSessionId);return{id:f.claudeSessionId,projectId:rs(f.projectName),projectName:f.projectName,projectPath:f.projectPath,claudeSessionId:f.claudeSessionId,summary:h?.title??f.summary,firstPrompt:f.firstPrompt,messageCount:f.messageCount??0,lastMessageTime:f.lastMessageTime,type:"cli",hasProcess:!1}}),u=[...o,...l].filter(f=>f.claudeSessionId).sort((f,h)=>(h.lastMessageTime??0)-(f.lastMessageTime??0)).slice(0,100),p=u.filter((f,h,y)=>y.findIndex(_=>_.claudeSessionId===f.claudeSessionId)!==h);p.length>0&&v.error(`Duplicate sessions detected: ${p.map(f=>`${f.claudeSessionId?.slice(0,8)} via ${f.projectPath}`).join(", ")}`);let g=new Map;for(let f of u){let h=f.projectName;g.set(h,(g.get(h)??0)+1)}v.info(`Sessions response: ${u.length} total (${o.length} managed, ${l.length} CLI)`);for(let[f,h]of g)v.info(` ${f} -- ${h} sessions`);console.log(m.dim(` Synced ${u.length} session${u.length!==1?"s":""} with app`));for(let f=0;f<u.length;f+=Ns){let h=u.slice(f,f+Ns),y=f+Ns>=u.length;t.sendFn({type:"sessions_response",sessionId:null,timestamp:Date.now(),payload:{sessions:h,done:y}})}u.length===0&&t.sendFn({type:"sessions_response",sessionId:null,timestamp:Date.now(),payload:{sessions:[],done:!0}});for(let f of t.sessionMgr.getPendingApprovals())t.sendFn({type:"tool_approval_request",sessionId:f.sessionId,timestamp:Date.now(),payload:{approvalId:f.approvalId,tool:f.tool,description:f.description,command:f.command}})}async function Lh(t){let e=t.payload.sessionId;if(!e||!ol(e)){t.sendFn({type:"error",sessionId:null,timestamp:Date.now(),payload:{code:"INVALID_REQUEST",message:"No sessionId provided for history request"}});return}let n=t.sessionMgr.getSession(e),r,s;if(n?.claudeSessionId?(r=n.projectPath,s=n.claudeSessionId,v.info(`History: managed session ${e} \u2192 claude=${s?.slice(0,8)} path=${r}`)):(s=t.payload.claudeSessionId,s&&he.test(s)&&(r=fs(new Set).find(y=>y.claudeSessionId===s)?.projectPath),v.info(`History: CLI session ${e} \u2192 claude=${s?.slice(0,8)} path=${r??"not found"}`)),!r||!s||!he.test(s)){t.sendFn({type:"session_history_response",sessionId:e,timestamp:Date.now(),payload:{sessionId:e,messages:[]}});return}v.info(`History: reading transcript for ${s?.slice(0,8)} at ${r}`);let o=us(r,s).map(f=>{let h=f.timestamp?new Date(f.timestamp).getTime():0;return{id:`hist_${il.createHash("sha256").update(`${f.role}
|
|
50
51
|
${h}
|
|
51
52
|
${(f.content??"").slice(0,200)}`).digest("hex").slice(0,12)}`,role:f.role,content:f.content,timestamp:h||Date.now(),...f.toolUses?.length?{toolUses:f.toolUses}:{},...f.contentBlocks?.length?{contentBlocks:f.contentBlocks}:{}}}),a=t.sessionMgr.getResolvedApprovals(e);for(let f of a)o.push({id:`hist-approval-${f.approvalId}`,role:"assistant",content:"",timestamp:f.timestamp,toolApproval:{approvalId:f.approvalId,tool:f.tool,description:f.description,command:f.command,resolved:!0,approved:f.approved}});o.sort((f,h)=>h.timestamp-f.timestamp);let l=new Set,c=[];for(let f of o){let h=f.id;l.has(h)||(l.add(h),c.push(f))}let u=4e3;for(let f of c)typeof f.content=="string"&&f.content.length>u&&(f.content=f.content.slice(0,u)+`
|
|
52
53
|
|
|
53
|
-
\u2026(truncated)`);let p=await Za(c,!0),g=c.length;v.info(`History: sending ${g} messages in ${p.length} batch(es) (deflate) for ${s?.slice(0,8)}`);for(let f=0;f<p.length;f++){let h=f===p.length-1;t.sendFn({type:"session_history_response",sessionId:e,timestamp:Date.now(),payload:{sessionId:e,messages:p[f],done:h}})}g===0&&t.sendFn({type:"session_history_response",sessionId:e,timestamp:Date.now(),payload:{sessionId:e,messages:[],done:!0}})}function ph(t){d.verifyCodeResolve&&(d.verifyCodeResolve(t),d.verifyCodeResolve=null)}function hh(t){t({type:"hello",sessionId:null,timestamp:Date.now(),payload:{appVersion:z,protocolVersion:3,capabilities:["deflate",...fe()?["wake"]:[]]}})}function gh(t){let{appVersion:e,protocolVersion:n,capabilities:r}=t.payload;e&&(d.peerAppVersion=e),r&&(d.peerCapabilities=r),v.info(`hello received: appVersion=${e} proto=${n} caps=${(r??[]).join(",")}`),console.log(m.dim(` App connected (v${e||"unknown"})`)),t.sendFn({type:"hello_ack",sessionId:null,timestamp:Date.now(),payload:{appVersion:z,protocolVersion:3,capabilities:["deflate",...fe()?["wake"]:[]],...fe()?{wakeState:d.wakeState,...d.wakeState==="awake"&&d.wakeExpiresAt?{expiresAt:d.wakeExpiresAt}:{}}:{}}})}function mh(t){let{appVersion:e,capabilities:n}=t;e&&(d.peerAppVersion=e),n&&(d.peerCapabilities=n),v.info(`hello_ack received: appVersion=${e} caps=${(n??[]).join(",")}`)}async function yh(t){let{wakeLockout:e}=d;if(e.lockedUntil){if(Date.now()<e.lockedUntil){t.sendFn({type:"wake_ack",sessionId:null,timestamp:Date.now(),payload:{success:!1,reason:"locked_out",lockoutExpiresAt:e.lockedUntil}});return}e.failedAttempts=0,e.lockedUntil=null}let n=D();if(!n?.wakePasswordHash){v.warn("wake message received but no wakePasswordHash configured");return}let r=t.payload.passwordHash;if(!r||!sr(r,n.wakePasswordHash)){e.failedAttempts++,v.warn(`Wake auth failed (attempt ${e.failedAttempts})`),console.log(m.yellow(` Wake auth failed (attempt ${e.failedAttempts})`));let u=e.failedAttempts;if(u>=6&&u<=9){let p=Math.pow(2,u-5)*1e3;await new Promise(g=>setTimeout(g,p))}if(u>=10){e.lockedUntil=Date.now()+1800*1e3,console.log(m.red(" Too many failed wake attempts \u2014 locked out for 30 minutes")),t.sendFn({type:"wake_ack",sessionId:null,timestamp:Date.now(),payload:{success:!1,reason:"locked_out",lockoutExpiresAt:e.lockedUntil}});return}t.sendFn({type:"wake_ack",sessionId:null,timestamp:Date.now(),payload:{success:!1,reason:"invalid_password",remainingAttempts:10-e.failedAttempts}});return}e.failedAttempts=0,e.lockedUntil=null;let s=72,i=t.payload.requestedDuration,o=typeof i=="number"&&i>0&&isFinite(i)?Math.min(i,s):Zt(),a=o*60*60*1e3,l=Date.now()+a;d.machine.state==="paired_sleeping"&&d.machine.transition({type:"WAKE"}),d.wakeExpiresAt=l,Oe(l),d.wakeTimer&&clearTimeout(d.wakeTimer),d.wakeTimer=setTimeout(()=>{As("timer_expired",t.sendFn)},a);let c=new Date().toLocaleTimeString();Me(["UNLOCKED",`Unlocked for ${o} hours.`],u=>m.green(u)),console.log(m.dim(` ${c}`)),console.log(),t.sendFn({type:"wake_ack",sessionId:null,timestamp:Date.now(),payload:{success:!0,expiresAt:l,duration:o}})}function As(t,e){d.machine.state==="paired"&&d.machine.transition({type:"SLEEP"}),d.wakeExpiresAt=null,Oe(null),d.wakeTimer&&(clearTimeout(d.wakeTimer),d.wakeTimer=null);let n=new Date().toLocaleTimeString();Me(["LOCKED","Remote access is locked.","Unlock from app or terminal."],r=>m.yellow(r)),console.log(m.dim(` ${n} \u2014 ${t}`)),console.log(),e({type:"sleep_notify",sessionId:null,timestamp:Date.now(),payload:{reason:t}}),d.onSleepTransition?.()}function _h(t){if(d.machine.transition({type:"REGISTERED",hasSharedSecret:!!d.sharedSecret}),d.inSetupMode){d.registeredResolve&&(d.registeredResolve(),d.registeredResolve=null);return}console.log(m.green(" Connected to relay".padEnd(50))+m.green("[connected]")),d.sharedSecret?(console.log(m.green(" Paired with BeachViber App".padEnd(50))+m.green("[encrypted]")),d.machine.state==="paired"&&fe()&&!d.wakeExpiresAt&&(d.machine.transition({type:"SLEEP"}),d.onSleepTransition?.()),console.log(),console.log(m.bold.green(" \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510")),console.log(m.bold.green(" \u2502 \u{1F512} End-to-end encryption active \u2502")),console.log(m.bold.green(" \u2502 \u2502")),console.log(m.bold.green(" \u2502")+m.dim(" All messages between this device and your ")+m.bold.green("\u2502")),console.log(m.bold.green(" \u2502")+m.dim(" phone are encrypted. No one \u2014 not even the ")+m.bold.green("\u2502")),console.log(m.bold.green(" \u2502")+m.dim(" relay server \u2014 can read them. ")+m.bold.green("\u2502")),console.log(m.bold.green(" \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"))):console.log(m.yellow(" Waiting for phone to pair...".padEnd(50))+m.yellow("[pairing]")),console.log(),d.registeredResolve&&(d.registeredResolve(),d.registeredResolve=null)}function wh(t){let e=t.reason||"none";if(v.warn(`force_disconnect received (reason=${e})`),U("force_disconnect","session","warn",`Force disconnect received (reason=${e})`,{reason:e}),e==="device_id_conflict"){console.log(m.yellow(" Another instance connected \u2014 will reconnect..."));return}console.log(),console.log(m.yellow(" Disconnected by remote \u2014 session ended.")),console.log(m.dim(" Will re-authenticate on next connection.")),console.log(),d.machine.transition({type:"FORCE_DISCONNECT"}),d.deviceToken=""}function Sh(t){if(console.error(m.red(` Error: ${t.code} \u2014 ${t.message}`)),t.code==="NOT_REGISTERED"){v.warn("Clearing deviceToken (reason: relay error NOT_REGISTERED -- token no longer valid)"),U("token_cleared","authentication","warn","Token cleared -- relay returned NOT_REGISTERED",{reason:"NOT_REGISTERED"}),d.machine.transition({type:"FORCE_DISCONNECT"});let e=D();e&&(delete e.deviceToken,G(e)),d.deviceToken=""}}async function Os(t,e,n,r){let s;try{s=JSON.parse(t)}catch{return v.error("Failed to parse message"),{projects:n}}let i=!1,o;s.type==="relay"&&s.payload&&(o=s._replyTo,s=s.payload,i=!0);let a=s.type;if(!Zp[d.connectionPhase].has(a))return d.connectionPhase==="paired_sleeping"&&i&&Je.has(a)&&(o?_=>e({..._,_replyTo:o}):e)({type:"error",sessionId:s.sessionId??null,timestamp:Date.now(),payload:{code:"DESKTOP_SLEEPING",message:"Remote access is locked \u2014 unlock it first"}}),v.error(`Rejected message type "${a}" in ${d.connectionPhase} phase`),U("phase_gate_rejected","rejection","warn",`Rejected "${a}" in ${d.connectionPhase} phase`,{messageType:a,phase:d.connectionPhase}),{projects:n};if(!i&&!new Set(["registered","error","force_disconnect","heartbeat_ack"]).has(a))return v.error(`Rejected non-relayed "${a}" message`),U("non_relayed_rejected","rejection","warn",`Rejected non-relayed "${a}" message`,{messageType:a}),{projects:n};if(d.sharedSecret&&i&&Je.has(a)&&!s.encrypted)return v.error(`Rejected unencrypted peer message "${a}" (shared secret exists)`),U("unencrypted_rejected","rejection","critical",`Rejected unencrypted peer message "${a}"`,{messageType:a}),{projects:n};if(s.encrypted){if(!d.sharedSecret)return v.error("Received encrypted message but no shared secret is available"),U("missing_shared_secret","crypto","critical","Received encrypted message but no shared secret",{messageType:a}),{projects:n};let y=s.encrypted;if(zp(y.nonce))return v.error(`Rejected duplicate nonce for "${a}" (replay detected)`),U("nonce_replay_detected","crypto","critical",`Rejected duplicate nonce for "${a}"`,{messageType:a,noncePrefix:y.nonce.slice(0,8)}),{projects:n};try{s.payload=ja(y,d.sharedSecret),delete s.encrypted}catch(I){return v.error(`Decryption failed for "${a}" (key=${Gp(d.sharedSecret)}, nonce=${y.nonce.slice(0,8)}\u2026, ct_len=${y.ciphertext.length}):`,I),U("decryption_failed","crypto","critical",`Decryption failed for "${a}"`,{messageType:a,noncePrefix:y.nonce.slice(0,8),ciphertextLength:y.ciphertext.length}),{projects:n}}Jp(y.nonce);let _=s.payload;if(!_||typeof _._ts!="number")return v.error(`Rejected encrypted message "${a}" -- missing mandatory _ts timestamp`),U("missing_timestamp","crypto","critical",`Rejected "${a}" -- missing mandatory _ts timestamp`,{messageType:a}),{projects:n};let w=Date.now()-_._ts;if(w>6e4||w<-3e4)return v.error(`Rejected replayed message "${a}" (age: ${w}ms)`),U("replayed_message","crypto","critical",`Rejected replayed message "${a}" (age: ${w}ms)`,{messageType:a,ageMs:w}),{projects:n};delete _._ts}let u=s.sessionId,p=u&&Ja(u)?u:null,g=s.payload||{},f=o?y=>e({...y,_replyTo:o}):e;o&&(r.lastPhoneReplyTo=o),r.setPhoneSendFn(e);let h={sendFn:f,sessionMgr:r,sessionId:p,payload:g,projects:n};if(a!=="heartbeat_ack"&&a!=="registered"&&v.info(`MSG type="${a}" sessionId=${p||"null"} payloadKeys=${Object.keys(g).join(",")||"none"}`),a==="wake")return await yh(h),{projects:h.projects};if(a==="force_sleep")return As("force_sleep",f),{projects:h.projects};switch(a){case"projects_request":return{projects:await th(h)};case"session_create":await nh(h);break;case"session_end":rh(h);break;case"session_delete":await sh(h);break;case"rename_session":oh(h);break;case"prompt":await ah(h);break;case"tool_approval_response":lh(h);break;case"sticky_approvals_clear":ch(h);break;case"process_stop":uh(h);break;case"sessions_request":el(h);break;case"session_status_request":dh(h);break;case"session_history_request":await fh(h);break;case"verify_code_ack":ph(g);break;case"hello":gh(h);break;case"hello_ack":mh(g);break;case"wake":case"wake_ack":case"sleep_notify":break;case"registered":_h(h);break;case"force_disconnect":wh(g);break;case"error":Sh(g);break;default:break}return{projects:h.projects}}async function Ns(t){hh(t);let e=await wt();d.projects=e,Xa(t,e);let n=Te();el({sendFn:t,sessionMgr:n,sessionId:null,payload:{},projects:e})}function Ls(t,e){return Math.min(t*2,e)}var v,Yp,nn,Zp,xs,Rs,Ps,Xp,Qe=K(()=>{"use strict";ct();Fn();bt();os();bt();pe();Rt();ut();Is();oe();Jt();v=M("ws");Yp=9e4,nn=new Map;Zp={registering:new Set(["registered","error","force_disconnect"]),pairing:new Set(["registered","verify_code_ack","error","force_disconnect","heartbeat_ack"]),paired:new Set([...Je,"error","force_disconnect","heartbeat_ack"]),paired_sleeping:new Set(["wake","force_sleep","error","force_disconnect","heartbeat_ack","hello","hello_ack"])},xs=10,Rs=15,Ps=1e4,Xp=5});var Ms=S((m0,nl)=>{nl.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var De=S(Xe=>{var Ds,Ch=[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];Xe.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};Xe.getSymbolTotalCodewords=function(e){return Ch[e]};Xe.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Xe.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Ds=e};Xe.isKanjiModeEnabled=function(){return typeof Ds<"u"};Xe.toSJIS=function(e){return Ds(e)}});var lr=S(ne=>{ne.L={bit:1};ne.M={bit:0};ne.Q={bit:3};ne.H={bit:2};function Ih(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ne.L;case"m":case"medium":return ne.M;case"q":case"quartile":return ne.Q;case"h":case"high":return ne.H;default:throw new Error("Unknown EC Level: "+t)}}ne.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ne.from=function(e,n){if(ne.isValid(e))return e;try{return Ih(e)}catch{return n}}});var il=S((w0,sl)=>{function rl(){this.buffer=[],this.length=0}rl.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++}};sl.exports=rl});var al=S((S0,ol)=>{function rn(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)}rn.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};rn.prototype.get=function(t,e){return this.data[t*this.size+e]};rn.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};rn.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};ol.exports=rn});var ll=S(cr=>{var xh=De().getSymbolSize;cr.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=xh(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()};cr.getPositions=function(e){let n=[],r=cr.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 dl=S(ul=>{var Rh=De().getSymbolSize,cl=7;ul.getPositions=function(e){let n=Rh(e);return[[0,0],[n-cl,0],[0,n-cl]]}});var fl=S(O=>{O.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var et={N1:3,N2:3,N3:40,N4:10};O.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};O.from=function(e){return O.isValid(e)?parseInt(e,10):void 0};O.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+=et.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(r+=et.N1+(i-5)),a=u,i=1)}s>=5&&(r+=et.N1+(s-5)),i>=5&&(r+=et.N1+(i-5))}return r};O.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*et.N2};O.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*et.N3};O.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)*et.N4};function Ph(t,e,n){switch(t){case O.Patterns.PATTERN000:return(e+n)%2===0;case O.Patterns.PATTERN001:return e%2===0;case O.Patterns.PATTERN010:return n%3===0;case O.Patterns.PATTERN011:return(e+n)%3===0;case O.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case O.Patterns.PATTERN101:return e*n%2+e*n%3===0;case O.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case O.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}O.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,Ph(e,i,s))};O.getBestMask=function(e,n){let r=Object.keys(O.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){n(o),O.applyMask(o,e);let a=O.getPenaltyN1(e)+O.getPenaltyN2(e)+O.getPenaltyN3(e)+O.getPenaltyN4(e);O.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var Us=S($s=>{var $e=lr(),ur=[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],dr=[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];$s.getBlocksCount=function(e,n){switch(n){case $e.L:return ur[(e-1)*4+0];case $e.M:return ur[(e-1)*4+1];case $e.Q:return ur[(e-1)*4+2];case $e.H:return ur[(e-1)*4+3];default:return}};$s.getTotalCodewordsCount=function(e,n){switch(n){case $e.L:return dr[(e-1)*4+0];case $e.M:return dr[(e-1)*4+1];case $e.Q:return dr[(e-1)*4+2];case $e.H:return dr[(e-1)*4+3];default:return}}});var pl=S(pr=>{var sn=new Uint8Array(512),fr=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)sn[n]=e,fr[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)sn[n]=sn[n-255]})();pr.log=function(e){if(e<1)throw new Error("log("+e+")");return fr[e]};pr.exp=function(e){return sn[e]};pr.mul=function(e,n){return e===0||n===0?0:sn[fr[e]+fr[n]]}});var hl=S(on=>{var Fs=pl();on.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]^=Fs.mul(e[s],n[i]);return r};on.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]^=Fs.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};on.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=on.mul(n,new Uint8Array([1,Fs.exp(r)]));return n}});var yl=S((I0,ml)=>{var gl=hl();function js(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}js.prototype.initialize=function(e){this.degree=e,this.genPoly=gl.generateECPolynomial(this.degree)};js.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=gl.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};ml.exports=js});var qs=S(_l=>{_l.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Ks=S(ve=>{var wl="[0-9]+",Ah="[A-Z $%*+\\-./:]+",an="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";an=an.replace(/u/g,"\\u");var Oh="(?:(?![A-Z0-9 $%*+\\-./:]|"+an+`)(?:.|[\r
|
|
54
|
-
]))+`;
|
|
55
|
-
Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};
|
|
56
|
-
Suggested mode is: `+P.toString(r));switch(n===P.KANJI&&!
|
|
54
|
+
\u2026(truncated)`);let p=await ll(c,!0),g=c.length;v.info(`History: sending ${g} messages in ${p.length} batch(es) (deflate) for ${s?.slice(0,8)}`);for(let f=0;f<p.length;f++){let h=f===p.length-1;t.sendFn({type:"session_history_response",sessionId:e,timestamp:Date.now(),payload:{sessionId:e,messages:p[f],done:h}})}g===0&&t.sendFn({type:"session_history_response",sessionId:e,timestamp:Date.now(),payload:{sessionId:e,messages:[],done:!0}})}function Bh(t){d.verifyCodeResolve&&(d.verifyCodeResolve(t),d.verifyCodeResolve=null)}function Mh(t){t({type:"hello",sessionId:null,timestamp:Date.now(),payload:{appVersion:z,protocolVersion:3,capabilities:["deflate",...fe()?["wake"]:[]]}})}function Dh(t){let{appVersion:e,protocolVersion:n,capabilities:r}=t.payload;e&&(d.peerAppVersion=e),r&&(d.peerCapabilities=r),v.info(`hello received: appVersion=${e} proto=${n} caps=${(r??[]).join(",")}`),console.log(m.dim(` App connected (v${e||"unknown"})`)),t.sendFn({type:"hello_ack",sessionId:null,timestamp:Date.now(),payload:{appVersion:z,protocolVersion:3,capabilities:["deflate",...fe()?["wake"]:[]],...fe()?{wakeState:d.wakeState,...d.wakeState==="awake"&&d.wakeExpiresAt?{expiresAt:d.wakeExpiresAt}:{}}:{}}})}function $h(t){let{appVersion:e,capabilities:n}=t;e&&(d.peerAppVersion=e),n&&(d.peerCapabilities=n),v.info(`hello_ack received: appVersion=${e} caps=${(n??[]).join(",")}`)}async function Uh(t){let{wakeLockout:e}=d;if(e.lockedUntil){if(Date.now()<e.lockedUntil){t.sendFn({type:"wake_ack",sessionId:null,timestamp:Date.now(),payload:{success:!1,reason:"locked_out",lockoutExpiresAt:e.lockedUntil}});return}e.failedAttempts=0,e.lockedUntil=null}let n=D();if(!n?.wakePasswordHash){v.warn("wake message received but no wakePasswordHash configured");return}let r=t.payload.passwordHash;if(!r||!or(r,n.wakePasswordHash)){e.failedAttempts++,v.warn(`Wake auth failed (attempt ${e.failedAttempts})`),console.log(m.yellow(` Wake auth failed (attempt ${e.failedAttempts})`));let u=e.failedAttempts;if(u>=6&&u<=9){let p=Math.pow(2,u-5)*1e3;await new Promise(g=>setTimeout(g,p))}if(u>=10){e.lockedUntil=Date.now()+1800*1e3,console.log(m.red(" Too many failed wake attempts \u2014 locked out for 30 minutes")),t.sendFn({type:"wake_ack",sessionId:null,timestamp:Date.now(),payload:{success:!1,reason:"locked_out",lockoutExpiresAt:e.lockedUntil}});return}t.sendFn({type:"wake_ack",sessionId:null,timestamp:Date.now(),payload:{success:!1,reason:"invalid_password",remainingAttempts:10-e.failedAttempts}});return}e.failedAttempts=0,e.lockedUntil=null;let s=72,i=t.payload.requestedDuration,o=typeof i=="number"&&i>0&&isFinite(i)?Math.min(i,s):Xt(),a=o*60*60*1e3,l=Date.now()+a;d.machine.state==="paired_sleeping"&&d.machine.transition({type:"WAKE"}),d.wakeExpiresAt=l,Ae(l),d.wakeTimer&&clearTimeout(d.wakeTimer),d.wakeTimer=setTimeout(()=>{Bs("timer_expired",t.sendFn)},a);let c=new Date().toLocaleTimeString();Me(["UNLOCKED",`Unlocked for ${o} hours.`],u=>m.green(u)),console.log(m.dim(` ${c}`)),console.log(),t.sendFn({type:"wake_ack",sessionId:null,timestamp:Date.now(),payload:{success:!0,expiresAt:l,duration:o}})}function Bs(t,e){d.machine.state==="paired"&&d.machine.transition({type:"SLEEP"}),d.wakeExpiresAt=null,Ae(null),d.wakeTimer&&(clearTimeout(d.wakeTimer),d.wakeTimer=null);let n=new Date().toLocaleTimeString();Me(["LOCKED","Remote access is locked.","Unlock from app or terminal."],r=>m.yellow(r)),console.log(m.dim(` ${n} \u2014 ${t}`)),console.log(),e({type:"sleep_notify",sessionId:null,timestamp:Date.now(),payload:{reason:t}}),d.onSleepTransition?.()}function Fh(t){if(d.machine.transition({type:"REGISTERED",hasSharedSecret:!!d.sharedSecret}),d.inSetupMode){d.registeredResolve&&(d.registeredResolve(),d.registeredResolve=null);return}console.log(m.green(" Connected to relay".padEnd(50))+m.green("[connected]")),d.sharedSecret?(console.log(m.green(" Paired with BeachViber App".padEnd(50))+m.green("[encrypted]")),d.machine.state==="paired"&&fe()&&!d.wakeExpiresAt&&(d.machine.transition({type:"SLEEP"}),d.onSleepTransition?.()),console.log(),console.log(m.bold.green(" \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510")),console.log(m.bold.green(" \u2502 \u{1F512} End-to-end encryption active \u2502")),console.log(m.bold.green(" \u2502 \u2502")),console.log(m.bold.green(" \u2502")+m.dim(" All messages between this device and your ")+m.bold.green("\u2502")),console.log(m.bold.green(" \u2502")+m.dim(" phone are encrypted. No one \u2014 not even the ")+m.bold.green("\u2502")),console.log(m.bold.green(" \u2502")+m.dim(" relay server \u2014 can read them. ")+m.bold.green("\u2502")),console.log(m.bold.green(" \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"))):console.log(m.yellow(" Waiting for phone to pair...".padEnd(50))+m.yellow("[pairing]")),console.log(),d.registeredResolve&&(d.registeredResolve(),d.registeredResolve=null)}function jh(t){let e=t.reason||"none";if(v.warn(`force_disconnect received (reason=${e})`),U("force_disconnect","session","warn",`Force disconnect received (reason=${e})`,{reason:e}),e==="device_id_conflict"){console.log(m.yellow(" Another instance connected \u2014 will reconnect..."));return}console.log(),console.log(m.yellow(" Disconnected by remote \u2014 session ended.")),console.log(m.dim(" Will re-authenticate on next connection.")),console.log(),d.machine.transition({type:"FORCE_DISCONNECT"}),d.deviceToken=""}function qh(t){if(console.error(m.red(` Error: ${t.code} \u2014 ${t.message}`)),t.code==="NOT_REGISTERED"){v.warn("Clearing deviceToken (reason: relay error NOT_REGISTERED -- token no longer valid)"),U("token_cleared","authentication","warn","Token cleared -- relay returned NOT_REGISTERED",{reason:"NOT_REGISTERED"}),d.machine.transition({type:"FORCE_DISCONNECT"});let e=D();e&&(delete e.deviceToken,G(e)),d.deviceToken=""}}async function Ms(t,e,n,r){let s;try{s=JSON.parse(t)}catch{return v.error("Failed to parse message"),{projects:n}}let i=!1,o;s.type==="relay"&&s.payload&&(o=s._replyTo,s=s.payload,i=!0);let a=s.type;if(!Sh[d.connectionPhase].has(a))return d.connectionPhase==="paired_sleeping"&&i&&Ze.has(a)&&(o?_=>e({..._,_replyTo:o}):e)({type:"error",sessionId:s.sessionId??null,timestamp:Date.now(),payload:{code:"DESKTOP_SLEEPING",message:"Remote access is locked \u2014 unlock it first"}}),v.error(`Rejected message type "${a}" in ${d.connectionPhase} phase`),U("phase_gate_rejected","rejection","warn",`Rejected "${a}" in ${d.connectionPhase} phase`,{messageType:a,phase:d.connectionPhase}),{projects:n};if(!i&&!new Set(["registered","error","force_disconnect","heartbeat_ack"]).has(a))return v.error(`Rejected non-relayed "${a}" message`),U("non_relayed_rejected","rejection","warn",`Rejected non-relayed "${a}" message`,{messageType:a}),{projects:n};if(d.sharedSecret&&i&&Ze.has(a)&&!s.encrypted)return v.error(`Rejected unencrypted peer message "${a}" (shared secret exists)`),U("unencrypted_rejected","rejection","critical",`Rejected unencrypted peer message "${a}"`,{messageType:a}),{projects:n};if(s.encrypted){if(!d.sharedSecret)return v.error("Received encrypted message but no shared secret is available"),U("missing_shared_secret","crypto","critical","Received encrypted message but no shared secret",{messageType:a}),{projects:n};let y=s.encrypted;if(yh(y.nonce))return v.error(`Rejected duplicate nonce for "${a}" (replay detected)`),U("nonce_replay_detected","crypto","critical",`Rejected duplicate nonce for "${a}"`,{messageType:a,noncePrefix:y.nonce.slice(0,8)}),{projects:n};try{s.payload=Qa(y,d.sharedSecret),delete s.encrypted}catch(x){return v.error(`Decryption failed for "${a}" (key=${gh(d.sharedSecret)}, nonce=${y.nonce.slice(0,8)}\u2026, ct_len=${y.ciphertext.length}):`,x),U("decryption_failed","crypto","critical",`Decryption failed for "${a}"`,{messageType:a,noncePrefix:y.nonce.slice(0,8),ciphertextLength:y.ciphertext.length}),{projects:n}}_h(y.nonce);let _=s.payload;if(!_||typeof _._ts!="number")return v.error(`Rejected encrypted message "${a}" -- missing mandatory _ts timestamp`),U("missing_timestamp","crypto","critical",`Rejected "${a}" -- missing mandatory _ts timestamp`,{messageType:a}),{projects:n};let w=Date.now()-_._ts;if(w>6e4||w<-3e4)return v.error(`Rejected replayed message "${a}" (age: ${w}ms)`),U("replayed_message","crypto","critical",`Rejected replayed message "${a}" (age: ${w}ms)`,{messageType:a,ageMs:w}),{projects:n};delete _._ts}let u=s.sessionId,p=u&&ol(u)?u:null,g=s.payload||{},f=o?y=>e({...y,_replyTo:o}):e;o&&(r.lastPhoneReplyTo=o),r.setPhoneSendFn(e);let h={sendFn:f,sessionMgr:r,sessionId:p,payload:g,projects:n};if(a!=="heartbeat_ack"&&a!=="registered"&&v.info(`MSG type="${a}" sessionId=${p||"null"} payloadKeys=${Object.keys(g).join(",")||"none"}`),a==="wake")return await Uh(h),{projects:h.projects};if(a==="force_sleep")return Bs("force_sleep",f),{projects:h.projects};switch(a){case"projects_request":return{projects:await Th(h)};case"session_create":await kh(h);break;case"session_end":vh(h);break;case"session_delete":await Ch(h);break;case"rename_session":xh(h);break;case"prompt":await Rh(h);break;case"tool_approval_response":Ph(h);break;case"sticky_approvals_clear":Ah(h);break;case"process_stop":Oh(h);break;case"sessions_request":ul(h);break;case"session_status_request":Nh(h);break;case"session_history_request":await Lh(h);break;case"verify_code_ack":Bh(g);break;case"hello":Dh(h);break;case"hello_ack":$h(g);break;case"wake":case"wake_ack":case"sleep_notify":break;case"registered":Fh(h);break;case"force_disconnect":jh(g);break;case"error":qh(g);break;case"image_upload_url":ja(g.requestId,{putUrl:g.putUrl,getUrl:g.getUrl,key:g.key});break;default:break}return{projects:h.projects}}async function Ds(t){Mh(t);let e=await Et();d.projects=e,cl(t,e);let n=ke();ul({sendFn:t,sessionMgr:n,sessionId:null,payload:{},projects:e})}function $s(t,e){return Math.min(t*2,e)}var v,mh,sn,Sh,Os,Ns,Ls,Eh,Xe=j(()=>{"use strict";dt();jn();Ct();ps();Ct();le();At();ft();As();ae();Qt();v=M("ws");mh=9e4,sn=new Map;Sh={registering:new Set(["registered","error","force_disconnect"]),pairing:new Set(["registered","verify_code_ack","error","force_disconnect","heartbeat_ack"]),paired:new Set([...Ze,"error","force_disconnect","heartbeat_ack"]),paired_sleeping:new Set(["wake","force_sleep","error","force_disconnect","heartbeat_ack","hello","hello_ack"])},Os=10,Ns=15,Ls=1e4,Eh=5});var Fs=S((V0,fl)=>{fl.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var De=S(tt=>{var js,Yh=[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];tt.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};tt.getSymbolTotalCodewords=function(e){return Yh[e]};tt.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};tt.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');js=e};tt.isKanjiModeEnabled=function(){return typeof js<"u"};tt.toSJIS=function(e){return js(e)}});var ur=S(re=>{re.L={bit:1};re.M={bit:0};re.Q={bit:3};re.H={bit:2};function zh(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return re.L;case"m":case"medium":return re.M;case"q":case"quartile":return re.Q;case"h":case"high":return re.H;default:throw new Error("Unknown EC Level: "+t)}}re.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};re.from=function(e,n){if(re.isValid(e))return e;try{return zh(e)}catch{return n}}});var gl=S((z0,hl)=>{function pl(){this.buffer=[],this.length=0}pl.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++}};hl.exports=pl});var yl=S((J0,ml)=>{function on(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)}on.prototype.set=function(t,e,n,r){let s=t*this.size+e;this.data[s]=n,r&&(this.reservedBit[s]=!0)};on.prototype.get=function(t,e){return this.data[t*this.size+e]};on.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};on.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};ml.exports=on});var _l=S(dr=>{var Jh=De().getSymbolSize;dr.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=Jh(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()};dr.getPositions=function(e){let n=[],r=dr.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 El=S(Sl=>{var Qh=De().getSymbolSize,wl=7;Sl.getPositions=function(e){let n=Qh(e);return[[0,0],[n-wl,0],[0,n-wl]]}});var bl=S(O=>{O.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var nt={N1:3,N2:3,N3:40,N4:10};O.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};O.from=function(e){return O.isValid(e)?parseInt(e,10):void 0};O.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+=nt.N1+(s-5)),o=u,s=1),u=e.get(c,l),u===a?i++:(i>=5&&(r+=nt.N1+(i-5)),a=u,i=1)}s>=5&&(r+=nt.N1+(s-5)),i>=5&&(r+=nt.N1+(i-5))}return r};O.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*nt.N2};O.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*nt.N3};O.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)*nt.N4};function Zh(t,e,n){switch(t){case O.Patterns.PATTERN000:return(e+n)%2===0;case O.Patterns.PATTERN001:return e%2===0;case O.Patterns.PATTERN010:return n%3===0;case O.Patterns.PATTERN011:return(e+n)%3===0;case O.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case O.Patterns.PATTERN101:return e*n%2+e*n%3===0;case O.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case O.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}O.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,Zh(e,i,s))};O.getBestMask=function(e,n){let r=Object.keys(O.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){n(o),O.applyMask(o,e);let a=O.getPenaltyN1(e)+O.getPenaltyN2(e)+O.getPenaltyN3(e)+O.getPenaltyN4(e);O.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var Ks=S(qs=>{var $e=ur(),fr=[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],pr=[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];qs.getBlocksCount=function(e,n){switch(n){case $e.L:return fr[(e-1)*4+0];case $e.M:return fr[(e-1)*4+1];case $e.Q:return fr[(e-1)*4+2];case $e.H:return fr[(e-1)*4+3];default:return}};qs.getTotalCodewordsCount=function(e,n){switch(n){case $e.L:return pr[(e-1)*4+0];case $e.M:return pr[(e-1)*4+1];case $e.Q:return pr[(e-1)*4+2];case $e.H:return pr[(e-1)*4+3];default:return}}});var Tl=S(gr=>{var an=new Uint8Array(512),hr=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)an[n]=e,hr[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)an[n]=an[n-255]})();gr.log=function(e){if(e<1)throw new Error("log("+e+")");return hr[e]};gr.exp=function(e){return an[e]};gr.mul=function(e,n){return e===0||n===0?0:an[hr[e]+hr[n]]}});var kl=S(ln=>{var Ws=Tl();ln.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]^=Ws.mul(e[s],n[i]);return r};ln.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]^=Ws.mul(n[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};ln.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=ln.mul(n,new Uint8Array([1,Ws.exp(r)]));return n}});var Il=S((rw,Cl)=>{var vl=kl();function Hs(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}Hs.prototype.initialize=function(e){this.degree=e,this.genPoly=vl.generateECPolynomial(this.degree)};Hs.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=vl.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};Cl.exports=Hs});var Vs=S(xl=>{xl.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Gs=S(Ce=>{var Rl="[0-9]+",Xh="[A-Z $%*+\\-./:]+",cn="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";cn=cn.replace(/u/g,"\\u");var eg="(?:(?![A-Z0-9 $%*+\\-./:]|"+cn+`)(?:.|[\r
|
|
55
|
+
]))+`;Ce.KANJI=new RegExp(cn,"g");Ce.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Ce.BYTE=new RegExp(eg,"g");Ce.NUMERIC=new RegExp(Rl,"g");Ce.ALPHANUMERIC=new RegExp(Xh,"g");var tg=new RegExp("^"+cn+"$"),ng=new RegExp("^"+Rl+"$"),rg=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Ce.testKanji=function(e){return tg.test(e)};Ce.testNumeric=function(e){return ng.test(e)};Ce.testAlphanumeric=function(e){return rg.test(e)}});var Ue=S($=>{var sg=Vs(),Ys=Gs();$.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};$.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};$.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};$.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};$.MIXED={bit:-1};$.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!sg.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};$.getBestModeForData=function(e){return Ys.testNumeric(e)?$.NUMERIC:Ys.testAlphanumeric(e)?$.ALPHANUMERIC:Ys.testKanji(e)?$.KANJI:$.BYTE};$.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};$.isValid=function(e){return e&&e.bit&&e.ccBits};function ig(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return $.NUMERIC;case"alphanumeric":return $.ALPHANUMERIC;case"kanji":return $.KANJI;case"byte":return $.BYTE;default:throw new Error("Unknown mode: "+t)}}$.from=function(e,n){if($.isValid(e))return e;try{return ig(e)}catch{return n}}});var Ll=S(rt=>{var mr=De(),og=Ks(),Pl=ur(),Fe=Ue(),zs=Vs(),Ol=7973,Al=mr.getBCHDigit(Ol);function ag(t,e,n){for(let r=1;r<=40;r++)if(e<=rt.getCapacity(r,n,t))return r}function Nl(t,e){return Fe.getCharCountIndicator(t,e)+4}function lg(t,e){let n=0;return t.forEach(function(r){let s=Nl(r.mode,e);n+=s+r.getBitsLength()}),n}function cg(t,e){for(let n=1;n<=40;n++)if(lg(t,n)<=rt.getCapacity(n,e,Fe.MIXED))return n}rt.from=function(e,n){return zs.isValid(e)?parseInt(e,10):n};rt.getCapacity=function(e,n,r){if(!zs.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=Fe.BYTE);let s=mr.getSymbolTotalCodewords(e),i=og.getTotalCodewordsCount(e,n),o=(s-i)*8;if(r===Fe.MIXED)return o;let a=o-Nl(r,e);switch(r){case Fe.NUMERIC:return Math.floor(a/10*3);case Fe.ALPHANUMERIC:return Math.floor(a/11*2);case Fe.KANJI:return Math.floor(a/13);case Fe.BYTE:default:return Math.floor(a/8)}};rt.getBestVersionForData=function(e,n){let r,s=Pl.from(n,Pl.M);if(Array.isArray(e)){if(e.length>1)return cg(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return ag(r.mode,r.getLength(),s)};rt.getEncodedBits=function(e){if(!zs.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;mr.getBCHDigit(n)-Al>=0;)n^=Ol<<mr.getBCHDigit(n)-Al;return e<<12|n}});var $l=S(Dl=>{var Js=De(),Ml=1335,ug=21522,Bl=Js.getBCHDigit(Ml);Dl.getEncodedBits=function(e,n){let r=e.bit<<3|n,s=r<<10;for(;Js.getBCHDigit(s)-Bl>=0;)s^=Ml<<Js.getBCHDigit(s)-Bl;return(r<<10|s)^ug}});var Fl=S((cw,Ul)=>{var dg=Ue();function Nt(t){this.mode=dg.NUMERIC,this.data=t.toString()}Nt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};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,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))};Ul.exports=Nt});var ql=S((uw,jl)=>{var fg=Ue(),Qs=["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 Lt(t){this.mode=fg.ALPHANUMERIC,this.data=t}Lt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Lt.prototype.getLength=function(){return this.data.length};Lt.prototype.getBitsLength=function(){return Lt.getBitsLength(this.data.length)};Lt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=Qs.indexOf(this.data[n])*45;r+=Qs.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(Qs.indexOf(this.data[n]),6)};jl.exports=Lt});var Wl=S((dw,Kl)=>{var pg=Ue();function Bt(t){this.mode=pg.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Bt.getBitsLength=function(e){return e*8};Bt.prototype.getLength=function(){return this.data.length};Bt.prototype.getBitsLength=function(){return Bt.getBitsLength(this.data.length)};Bt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Kl.exports=Bt});var Vl=S((fw,Hl)=>{var hg=Ue(),gg=De();function Mt(t){this.mode=hg.KANJI,this.data=t}Mt.getBitsLength=function(e){return e*13};Mt.prototype.getLength=function(){return this.data.length};Mt.prototype.getBitsLength=function(){return Mt.getBitsLength(this.data.length)};Mt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=gg.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]+`
|
|
56
|
+
Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};Hl.exports=Mt});var Gl=S((pw,Zs)=>{"use strict";var un={single_source_shortest_paths:function(t,e,n){var r={},s={};s[e]=0;var i=un.PriorityQueue.make();i.push(e,0);for(var o,a,l,c,u,p,g,f,h;!i.empty();){o=i.pop(),a=o.value,c=o.cost,u=t[a]||{};for(l in u)u.hasOwnProperty(l)&&(p=u[l],g=c+p,f=s[l],h=typeof s[l]>"u",(h||f>g)&&(s[l]=g,i.push(l,g),r[l]=a))}if(typeof n<"u"&&typeof s[n]>"u"){var y=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(y)}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=un.single_source_shortest_paths(t,e,n);return un.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=un.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 Zs<"u"&&(Zs.exports=un)});var tc=S(Dt=>{var P=Ue(),Jl=Fl(),Ql=ql(),Zl=Wl(),Xl=Vl(),dn=Gs(),yr=De(),mg=Gl();function Yl(t){return unescape(encodeURIComponent(t)).length}function fn(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 ec(t){let e=fn(dn.NUMERIC,P.NUMERIC,t),n=fn(dn.ALPHANUMERIC,P.ALPHANUMERIC,t),r,s;return yr.isKanjiModeEnabled()?(r=fn(dn.BYTE,P.BYTE,t),s=fn(dn.KANJI,P.KANJI,t)):(r=fn(dn.BYTE_KANJI,P.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 Xs(t,e){switch(e){case P.NUMERIC:return Jl.getBitsLength(t);case P.ALPHANUMERIC:return Ql.getBitsLength(t);case P.KANJI:return Xl.getBitsLength(t);case P.BYTE:return Zl.getBitsLength(t)}}function yg(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 _g(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case P.NUMERIC:e.push([r,{data:r.data,mode:P.ALPHANUMERIC,length:r.length},{data:r.data,mode:P.BYTE,length:r.length}]);break;case P.ALPHANUMERIC:e.push([r,{data:r.data,mode:P.BYTE,length:r.length}]);break;case P.KANJI:e.push([r,{data:r.data,mode:P.BYTE,length:Yl(r.data)}]);break;case P.BYTE:e.push([{data:r.data,mode:P.BYTE,length:Yl(r.data)}])}}return e}function wg(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 p=0;p<s.length;p++){let g=s[p];n[g]&&n[g].node.mode===c.mode?(r[g][u]=Xs(n[g].lastCount+c.length,c.mode)-Xs(n[g].lastCount,c.mode),n[g].lastCount+=c.length):(n[g]&&(n[g].lastCount=c.length),r[g][u]=Xs(c.length,c.mode)+4+P.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 zl(t,e){let n,r=P.getBestModeForData(t);if(n=P.from(e,r),n!==P.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+P.toString(n)+`.
|
|
57
|
+
Suggested mode is: `+P.toString(r));switch(n===P.KANJI&&!yr.isKanjiModeEnabled()&&(n=P.BYTE),n){case P.NUMERIC:return new Jl(t);case P.ALPHANUMERIC:return new Ql(t);case P.KANJI:return new Xl(t);case P.BYTE:return new Zl(t)}}Dt.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(zl(r,null)):r.data&&n.push(zl(r.data,r.mode)),n},[])};Dt.fromString=function(e,n){let r=ec(e,yr.isKanjiModeEnabled()),s=_g(r),i=wg(s,n),o=mg.find_path(i.map,"start","end"),a=[];for(let l=1;l<o.length-1;l++)a.push(i.table[o[l]].node);return Dt.fromArray(yg(a))};Dt.rawSplit=function(e){return Dt.fromArray(ec(e,yr.isKanjiModeEnabled()))}});var ii=S(nc=>{var wr=De(),ei=ur(),Sg=gl(),Eg=yl(),bg=_l(),Tg=El(),ri=bl(),si=Ks(),kg=Il(),_r=Ll(),vg=$l(),Cg=Ue(),ti=tc();function Ig(t,e){let n=t.size,r=Tg.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 xg(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 Rg(t,e){let n=bg.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 Pg(t,e){let n=t.size,r=_r.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 ni(t,e,n){let r=t.size,s=vg.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 Ag(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 Og(t,e,n){let r=new Sg;n.forEach(function(l){r.put(l.mode.bit,4),r.put(l.getLength(),Cg.getCharCountIndicator(l.mode,t)),l.write(r)});let s=wr.getSymbolTotalCodewords(t),i=si.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 Ng(r,t,e)}function Ng(t,e,n){let r=wr.getSymbolTotalCodewords(e),s=si.getTotalCodewordsCount(e,n),i=r-s,o=si.getBlocksCount(e,n),a=r%o,l=o-a,c=Math.floor(r/o),u=Math.floor(i/o),p=u+1,g=c-u,f=new kg(g),h=0,y=new Array(o),_=new Array(o),w=0,x=new Uint8Array(t.buffer);for(let b=0;b<o;b++){let I=b<l?u:p;y[b]=x.slice(h,h+I),_[b]=f.encode(y[b]),h+=I,w=Math.max(w,I)}let A=new Uint8Array(r),E=0,T,k;for(T=0;T<w;T++)for(k=0;k<o;k++)T<y[k].length&&(A[E++]=y[k][T]);for(T=0;T<g;T++)for(k=0;k<o;k++)A[E++]=_[k][T];return A}function Lg(t,e,n,r){let s;if(Array.isArray(t))s=ti.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let u=ti.rawSplit(t);c=_r.getBestVersionForData(u,n)}s=ti.fromString(t,c||40)}else throw new Error("Invalid data");let i=_r.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(`
|
|
57
58
|
The chosen QR Code version cannot contain this amount of data.
|
|
58
59
|
Minimum version required to store current data is: `+i+`.
|
|
59
|
-
`);let o=ug(e,n,s),a=yr.getSymbolSize(e),l=new Xh(a);return ig(l,e),og(l),ag(l,e),Zs(l,n,0),e>=7&&lg(l,e),cg(l,o),isNaN(r)&&(r=Xs.getBestMask(l,Zs.bind(null,l,n))),Xs.applyMask(r,l),Zs(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}Vl.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=Js.M,s,i;return typeof n<"u"&&(r=Js.from(n.errorCorrectionLevel,Js.M),s=mr.from(n.version),i=Xs.from(n.maskPattern),n.toSJISFunc&&yr.setToSJISFunction(n.toSJISFunc)),fg(e,s,r,i)}});var ni=S((F0,Yl)=>{"use strict";var pg=C("util"),Gl=C("stream"),le=Yl.exports=function(){Gl.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};pg.inherits(le,Gl);le.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))};le.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};le.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()))};le.prototype.destroySoon=le.prototype.end;le.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};le.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};le.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))};le.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)};le.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 si=S(ri=>{"use strict";var je=[{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]}];ri.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<je.length;a++){let l=je[a],c=i*l.x.length,u=o*l.y.length;for(let p=0;p<l.x.length&&l.x[p]<r;p++)c++;for(let p=0;p<l.y.length&&l.y[p]<s;p++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};ri.getInterlaceIterator=function(t){return function(e,n,r){let s=e%je[r].x.length,i=(e-s)/je[r].x.length*8+je[r].x[s],o=n%je[r].y.length,a=(n-o)/je[r].y.length*8+je[r].y[o];return i*4+a*t*4}}});var ii=S((q0,zl)=>{"use strict";zl.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 oi=S((K0,Ql)=>{"use strict";var hg=si(),gg=ii();function Jl(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var Mt=Ql.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=hg.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:Jl(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:Jl(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};Mt.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Mt.prototype._unFilterType1=function(t,e,n){let r=this._xComparison,s=r-1;for(let i=0;i<n;i++){let o=t[1+i],a=i>s?e[i-r]:0;e[i]=o+a}};Mt.prototype._unFilterType2=function(t,e,n){let r=this._lastLine;for(let s=0;s<n;s++){let i=t[1+s],o=r?r[s]:0;e[s]=i+o}};Mt.prototype._unFilterType3=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=Math.floor((c+l)/2);e[o]=a+u}};Mt.prototype._unFilterType4=function(t,e,n){let r=this._xComparison,s=r-1,i=this._lastLine;for(let o=0;o<n;o++){let a=t[1+o],l=i?i[o]:0,c=o>s?e[o-r]:0,u=o>s&&i?i[o-r]:0,p=gg(c,l,u);e[o]=a+p}};Mt.prototype._reverseFilterLine=function(t){let e=t[0],n,r=this._images[this._imageIndex],s=r.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var ec=S((W0,Xl)=>{"use strict";var mg=C("util"),Zl=ni(),yg=oi(),_g=Xl.exports=function(t){Zl.call(this);let e=[],n=this;this._filter=new yg(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};mg.inherits(_g,Zl)});var Dt=S((H0,tc)=>{"use strict";tc.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 ci=S((V0,nc)=>{"use strict";var ai=[];(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;ai[t]=e}})();var li=nc.exports=function(){this._crc=-1};li.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=ai[(this._crc^t[e])&255]^this._crc>>>8;return!0};li.prototype.crc32=function(){return this._crc^-1};li.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=ai[(e^t[n])&255]^e>>>8;return e^-1}});var ui=S((G0,rc)=>{"use strict";var F=Dt(),wg=ci(),q=rc.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[F.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[F.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[F.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[F.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[F.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[F.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(){}};q.prototype.start=function(){this.read(F.PNG_SIGNATURE.length,this._parseSignature.bind(this))};q.prototype._parseSignature=function(t){let e=F.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))};q.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!==F.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new wg,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))};q.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};q.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};q.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))};q.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};q.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 F.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=F.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&F.COLORTYPE_PALETTE),color:!!(s&F.COLORTYPE_COLOR),alpha:!!(s&F.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};q.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};q.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()};q.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};q.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===F.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===F.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===F.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};q.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};q.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/F.GAMMA_DIVISION),this._handleChunkEnd()};q.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};q.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===F.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()};q.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};q.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var di=S(ic=>{"use strict";var sc=si(),Sg=[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]}],Eg=[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 bg(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,p,g,f;switch(e){default:throw new Error("unrecognised depth");case 16:g=t[r],r++,n.push((i<<8)+g);break;case 4:g=i&15,f=i>>4,n.push(f,g);break;case 2:u=i&3,p=i>>2&3,g=i>>4&3,f=i>>6&3,n.push(f,g,p,u);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,c=i>>3&1,u=i>>4&1,p=i>>5&1,g=i>>6&1,f=i>>7&1,n.push(f,g,p,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 Tg(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 p=n(u,c,l);Sg[r](e,s,p,i),i+=r}return i}function kg(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 p=s.get(r),g=n(u,c,l);Eg[r](e,p,g,i)}s.resetAfterLine()}}ic.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=bg(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,p,g;if(o)p=sc.getImagePasses(n,r),g=sc.getInterlaceIterator(n,r);else{let f=0;g=function(){let h=f;return f+=4,h},p=[{width:n,height:r}]}for(let f=0;f<p.length;f++)s===8?u=Tg(p[f],l,g,i,t,u):kg(p[f],l,g,i,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var fi=S((z0,oc)=>{"use strict";function vg(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 Cg(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 Ig(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}}oc.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?vg(t,l,r,s,a):(o&&Cg(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),Ig(t,l,r,s,n))),l}});var cc=S((J0,lc)=>{"use strict";var xg=C("util"),pi=C("zlib"),ac=ni(),Rg=ec(),Pg=ui(),Ag=di(),Og=fi(),me=lc.exports=function(t){ac.call(this),this._parser=new Pg(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()};xg.inherits(me,ac);me.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};me.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=pi.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,pi.Z_MIN_CHUNK);this._inflate=pi.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)};me.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Rg(this._bitmapInfo)};me.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};me.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};me.prototype._simpleTransparency=function(){this._metaData.alpha=!0};me.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};me.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};me.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Ag.dataToBitMap(t,this._bitmapInfo);e=Og(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var dc=S((Q0,uc)=>{"use strict";var re=Dt();uc.exports=function(t,e,n,r){let s=[re.COLORTYPE_COLOR_ALPHA,re.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let h=(function(){let y=new ArrayBuffer(2);return new DataView(y).setInt16(0,256,!0),new Int16Array(y)[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=re.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=re.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,p=0,g=r.bgColor||{};g.red===void 0&&(g.red=o),g.green===void 0&&(g.green=o),g.blue===void 0&&(g.blue=o);function f(){let h,y,_,w=o;switch(r.inputColorType){case re.COLORTYPE_COLOR_ALPHA:w=i[u+3],h=i[u],y=i[u+1],_=i[u+2];break;case re.COLORTYPE_COLOR:h=i[u],y=i[u+1],_=i[u+2];break;case re.COLORTYPE_ALPHA:w=i[u+1],h=i[u],y=h,_=h;break;case re.COLORTYPE_GRAYSCALE:h=i[u],y=h,_=h;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(w/=o,h=Math.min(Math.max(Math.round((1-w)*g.red+w*h),0),o),y=Math.min(Math.max(Math.round((1-w)*g.green+w*y),0),o),_=Math.min(Math.max(Math.round((1-w)*g.blue+w*_),0),o))),{red:h,green:y,blue:_,alpha:w}}for(let h=0;h<n;h++)for(let y=0;y<e;y++){let _=f(i,u);switch(r.colorType){case re.COLORTYPE_COLOR_ALPHA:case re.COLORTYPE_COLOR:r.bitDepth===8?(c[p]=_.red,c[p+1]=_.green,c[p+2]=_.blue,s&&(c[p+3]=_.alpha)):(c.writeUInt16BE(_.red,p),c.writeUInt16BE(_.green,p+2),c.writeUInt16BE(_.blue,p+4),s&&c.writeUInt16BE(_.alpha,p+6));break;case re.COLORTYPE_ALPHA:case re.COLORTYPE_GRAYSCALE:{let w=(_.red+_.green+_.blue)/3;r.bitDepth===8?(c[p]=w,s&&(c[p+1]=_.alpha)):(c.writeUInt16BE(w,p),s&&c.writeUInt16BE(_.alpha,p+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,p+=l}return c}});var hc=S((Z0,pc)=>{"use strict";var fc=ii();function Ng(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function Lg(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function Bg(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 Mg(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 Dg(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 $g(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 Ug(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 Fg(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 jg(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]-fc(a,l,c);r[s+o]=u}}function qg(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]-fc(o,a,l);s+=Math.abs(c)}return s}var Kg={0:Ng,1:Bg,2:Dg,3:Ug,4:jg},Wg={0:Lg,1:Mg,2:$g,3:Fg,4:qg};pc.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 p=0;p<n;p++){if(i.length>1){let g=1/0;for(let f=0;f<i.length;f++){let h=Wg[i[f]](t,l,o,s);h<g&&(u=i[f],g=h)}}c[a]=u,a++,Kg[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var hi=S((X0,gc)=>{"use strict";var W=Dt(),Hg=ci(),Vg=dc(),Gg=hc(),Yg=C("zlib"),qe=gc.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||Yg.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:W.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:W.COLORTYPE_COLOR_ALPHA,[W.COLORTYPE_GRAYSCALE,W.COLORTYPE_COLOR,W.COLORTYPE_COLOR_ALPHA,W.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([W.COLORTYPE_GRAYSCALE,W.COLORTYPE_COLOR,W.COLORTYPE_COLOR_ALPHA,W.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};qe.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};qe.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};qe.prototype.filterData=function(t,e,n){let r=Vg(t,e,n,this._options),s=W.COLORTYPE_TO_BPP_MAP[this._options.colorType];return Gg(r,e,n,this._options,s)};qe.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(Hg.crc32(r.slice(4,r.length-4)),r.length-4),r};qe.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*W.GAMMA_DIVISION),0),this._packChunk(W.TYPE_gAMA,e)};qe.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(W.TYPE_IHDR,n)};qe.prototype.packIDAT=function(t){return this._packChunk(W.TYPE_IDAT,t)};qe.prototype.packIEND=function(){return this._packChunk(W.TYPE_IEND,null)}});var wc=S((ew,_c)=>{"use strict";var zg=C("util"),mc=C("stream"),Jg=Dt(),Qg=hi(),yc=_c.exports=function(t){mc.call(this);let e=t||{};this._packer=new Qg(e),this._deflate=this._packer.createDeflate(),this.readable=!0};zg.inherits(yc,mc);yc.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(Jg.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 vc=S((dn,kc)=>{"use strict";var Sc=C("assert").ok,$t=C("zlib"),Zg=C("util"),Ec=C("buffer").kMaxLength;function nt(t){if(!(this instanceof nt))return new nt(t);t&&t.chunkSize<$t.Z_MIN_CHUNK&&(t.chunkSize=$t.Z_MIN_CHUNK),$t.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 Xg(t){return new nt(t)}function bc(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}nt.prototype._processChunk=function(t,e,n){if(typeof n=="function")return $t.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 p(h,y){if(r._hadError)return;let _=i-y;if(Sc(_>=0,"have should not go down"),_>0){let w=r._buffer.slice(r._offset,r._offset+_);if(r._offset+=_,w.length>o&&(w=w.slice(0,o)),l.push(w),c+=w.length,o-=w.length,o===0)return!1}return(y===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),y===0?(a+=s-h,s=h,!0):!1}Sc(this._handle,"zlib binding closed");let g;do g=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),g=g||this._writeState;while(!this._hadError&&p(g[0],g[1]));if(this._hadError)throw u;if(c>=Ec)throw bc(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Ec.toString(16)+" bytes");let f=Buffer.concat(l,c);return bc(this),f};Zg.inherits(nt,$t.Inflate);function em(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=$t.Z_FINISH),t._processChunk(e,n)}function Tc(t,e){return em(new nt(e),t)}kc.exports=dn=Tc;dn.Inflate=nt;dn.createInflate=Xg;dn.inflateSync=Tc});var gi=S((tw,Ic)=>{"use strict";var Cc=Ic.exports=function(t){this._buffer=t,this._reads=[]};Cc.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Cc.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 Rc=S(xc=>{"use strict";var tm=gi(),nm=oi();xc.process=function(t,e){let n=[],r=new tm(t);return new nm(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Nc=S((rw,Oc)=>{"use strict";var Pc=!0,Ac=C("zlib"),rm=vc();Ac.deflateSync||(Pc=!1);var sm=gi(),im=Rc(),om=ui(),am=di(),lm=fi();Oc.exports=function(t,e){if(!Pc)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(k){n=k}let s;function i(k){s=k}function o(k){s.transColor=k}function a(k){s.palette=k}function l(){s.alpha=!0}let c;function u(k){c=k}let p=[];function g(k){p.push(k)}let f=new sm(t);if(new om(e,{read:f.read.bind(f),error:r,metadata:i,gamma:u,palette:a,transColor:o,inflateData:g,simpleTransparency:l}).start(),f.process(),n)throw n;let y=Buffer.concat(p);p.length=0;let _;if(s.interlace)_=Ac.inflateSync(y);else{let b=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;_=rm(y,{chunkSize:b,maxLength:b})}if(y=null,!_||!_.length)throw new Error("bad png - invalid inflate data response");let w=im.process(_,s);y=null;let I=am.dataToBitMap(w,s);w=null;let A=lm(I,s);return s.data=A,s.gamma=c||0,s}});var Dc=S((sw,Mc)=>{"use strict";var Lc=!0,Bc=C("zlib");Bc.deflateSync||(Lc=!1);var cm=Dt(),um=hi();Mc.exports=function(t,e){if(!Lc)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 um(n),s=[];s.push(Buffer.from(cm.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=Bc.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 $c=S(mi=>{"use strict";var dm=Nc(),fm=Dc();mi.read=function(t,e){return dm(t,e||{})};mi.write=function(t,e){return fm(t,e)}});var jc=S(Fc=>{"use strict";var pm=C("util"),Uc=C("stream"),hm=cc(),gm=wc(),mm=$c(),H=Fc.PNG=function(t){Uc.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 hm(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 gm(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"))};pm.inherits(H,Uc);H.sync=mm;H.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)};H.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};H.prototype.write=function(t){return this._parser.write(t),!0};H.prototype.end=function(t){this._parser.end(t)};H.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};H.prototype._gamma=function(t){this.gamma=t};H.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};H.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)};H.prototype.bitblt=function(t,e,n,r,s,i,o){return H.bitblt(this,t,e,n,r,s,i,o),this};H.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}};H.prototype.adjustGamma=function(){H.adjustGamma(this)}});var fn=S(rt=>{function qc(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}rt.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:n,color:{dark:qc(e.color.dark||"#000000ff"),light:qc(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};rt.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};rt.getImageWidth=function(e,n){let r=rt.getScale(e,n);return Math.floor((e+n.margin*2)*r)};rt.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=rt.getScale(s,r),a=Math.floor((s+r.margin*2)*o),l=r.margin*o,c=[r.color.light,r.color.dark];for(let u=0;u<a;u++)for(let p=0;p<a;p++){let g=(u*a+p)*4,f=r.color.light;if(u>=l&&p>=l&&u<a-l&&p<a-l){let h=Math.floor((u-l)/o),y=Math.floor((p-l)/o);f=c[i[h*s+y]?1:0]}e[g++]=f.r,e[g++]=f.g,e[g++]=f.b,e[g]=f.a}}});var Kc=S(ye=>{var ym=C("fs"),_m=jc().PNG,yi=fn();ye.render=function(e,n){let r=yi.getOptions(n),s=r.rendererOpts,i=yi.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new _m(s);return yi.qrToImageData(o.data,e,r),o};ye.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),ye.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};ye.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=ye.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()};ye.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=ym.createWriteStream(e);a.on("error",o),a.on("close",o),ye.renderToFileStream(a,n,r)};ye.renderToFileStream=function(e,n,r){ye.render(n,r).pack().pipe(e)}});var Wc=S(_r=>{var wm=fn(),Sm={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Em={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function bm(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}_r.render=function(t,e,n){let r=wm.getOptions(e),s=Sm;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=Em);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+`
|
|
60
|
-
`);let c=Array(r.margin+1).join(s.WW);a+=l;for(let u=0;u<i;u+=2){a+=c;for(let p=0;p<i;p++){let g=o[u*i+p],f=o[(u+1)*i+p];a+=
|
|
61
|
-
`}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};
|
|
60
|
+
`);let o=Og(e,n,s),a=wr.getSymbolSize(e),l=new Eg(a);return Ig(l,e),xg(l),Rg(l,e),ni(l,n,0),e>=7&&Pg(l,e),Ag(l,o),isNaN(r)&&(r=ri.getBestMask(l,ni.bind(null,l,n))),ri.applyMask(r,l),ni(l,n,r),{modules:l,version:e,errorCorrectionLevel:n,maskPattern:r,segments:s}}nc.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=ei.M,s,i;return typeof n<"u"&&(r=ei.from(n.errorCorrectionLevel,ei.M),s=_r.from(n.version),i=ri.from(n.maskPattern),n.toSJISFunc&&wr.setToSJISFunction(n.toSJISFunc)),Lg(e,s,r,i)}});var oi=S((mw,sc)=>{"use strict";var Bg=C("util"),rc=C("stream"),ue=sc.exports=function(){rc.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};Bg.inherits(ue,rc);ue.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))};ue.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};ue.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()))};ue.prototype.destroySoon=ue.prototype.end;ue.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};ue.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};ue.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))};ue.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)};ue.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 li=S(ai=>{"use strict";var je=[{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]}];ai.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<je.length;a++){let l=je[a],c=i*l.x.length,u=o*l.y.length;for(let p=0;p<l.x.length&&l.x[p]<r;p++)c++;for(let p=0;p<l.y.length&&l.y[p]<s;p++)u++;c>0&&u>0&&n.push({width:c,height:u,index:a})}return n};ai.getInterlaceIterator=function(t){return function(e,n,r){let s=e%je[r].x.length,i=(e-s)/je[r].x.length*8+je[r].x[s],o=n%je[r].y.length,a=(n-o)/je[r].y.length*8+je[r].y[o];return i*4+a*t*4}}});var ci=S((_w,ic)=>{"use strict";ic.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 ui=S((ww,ac)=>{"use strict";var Mg=li(),Dg=ci();function oc(t,e,n){let r=t*e;return n!==8&&(r=Math.ceil(r/(8/n))),r}var $t=ac.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=Mg.getImagePasses(n,r);for(let l=0;l<a.length;l++)this._images.push({byteWidth:oc(a[l].width,i,o),height:a[l].height,lineIndex:0})}else this._images.push({byteWidth:oc(n,i,o),height:r,lineIndex:0});o===8?this._xComparison=i:o===16?this._xComparison=i*2:this._xComparison=1};$t.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};$t.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}};$t.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}};$t.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}};$t.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,p=Dg(c,l,u);e[o]=a+p}};$t.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 uc=S((Sw,cc)=>{"use strict";var $g=C("util"),lc=oi(),Ug=ui(),Fg=cc.exports=function(t){lc.call(this);let e=[],n=this;this._filter=new Ug(t,{read:this.read.bind(this),write:function(r){e.push(r)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};$g.inherits(Fg,lc)});var Ut=S((Ew,dc)=>{"use strict";dc.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 pi=S((bw,fc)=>{"use strict";var di=[];(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;di[t]=e}})();var fi=fc.exports=function(){this._crc=-1};fi.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=di[(this._crc^t[e])&255]^this._crc>>>8;return!0};fi.prototype.crc32=function(){return this._crc^-1};fi.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=di[(e^t[n])&255]^e>>>8;return e^-1}});var hi=S((Tw,pc)=>{"use strict";var F=Ut(),jg=pi(),K=pc.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[F.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[F.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[F.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[F.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[F.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[F.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(){}};K.prototype.start=function(){this.read(F.PNG_SIGNATURE.length,this._parseSignature.bind(this))};K.prototype._parseSignature=function(t){let e=F.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))};K.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!==F.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new jg,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))};K.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};K.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};K.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))};K.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};K.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 F.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=F.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:r,interlace:!!a,palette:!!(s&F.COLORTYPE_PALETTE),color:!!(s&F.COLORTYPE_COLOR),alpha:!!(s&F.COLORTYPE_ALPHA),bpp:l,colorType:s}),this._handleChunkEnd()};K.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};K.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()};K.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};K.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===F.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===F.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===F.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};K.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};K.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/F.GAMMA_DIVISION),this._handleChunkEnd()};K.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};K.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===F.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()};K.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};K.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var gi=S(gc=>{"use strict";var hc=li(),qg=[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]}],Kg=[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 Wg(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,p,g,f;switch(e){default:throw new Error("unrecognised depth");case 16:g=t[r],r++,n.push((i<<8)+g);break;case 4:g=i&15,f=i>>4,n.push(f,g);break;case 2:u=i&3,p=i>>2&3,g=i>>4&3,f=i>>6&3,n.push(f,g,p,u);break;case 1:o=i&1,a=i>>1&1,l=i>>2&1,c=i>>3&1,u=i>>4&1,p=i>>5&1,g=i>>6&1,f=i>>7&1,n.push(f,g,p,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 Hg(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 p=n(u,c,l);qg[r](e,s,p,i),i+=r}return i}function Vg(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 p=s.get(r),g=n(u,c,l);Kg[r](e,p,g,i)}s.resetAfterLine()}}gc.dataToBitMap=function(t,e){let n=e.width,r=e.height,s=e.depth,i=e.bpp,o=e.interlace,a;s!==8&&(a=Wg(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,p,g;if(o)p=hc.getImagePasses(n,r),g=hc.getInterlaceIterator(n,r);else{let f=0;g=function(){let h=f;return f+=4,h},p=[{width:n,height:r}]}for(let f=0;f<p.length;f++)s===8?u=Hg(p[f],l,g,i,t,u):Vg(p[f],l,g,i,a,c);if(s===8){if(u!==t.length)throw new Error("extra data found")}else a.end();return l}});var mi=S((vw,mc)=>{"use strict";function Gg(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 Yg(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 zg(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}}mc.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?Gg(t,l,r,s,a):(o&&Yg(t,l,r,s,o),n!==8&&(n===16&&(l=Buffer.alloc(r*s*4)),zg(t,l,r,s,n))),l}});var wc=S((Cw,_c)=>{"use strict";var Jg=C("util"),yi=C("zlib"),yc=oi(),Qg=uc(),Zg=hi(),Xg=gi(),em=mi(),ye=_c.exports=function(t){yc.call(this),this._parser=new Zg(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()};Jg.inherits(ye,yc);ye.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};ye.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=yi.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,yi.Z_MIN_CHUNK);this._inflate=yi.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)};ye.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Qg(this._bitmapInfo)};ye.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};ye.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};ye.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ye.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ye.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};ye.prototype._complete=function(t){if(this.errord)return;let e;try{let n=Xg.dataToBitMap(t,this._bitmapInfo);e=em(n,this._bitmapInfo),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Ec=S((Iw,Sc)=>{"use strict";var se=Ut();Sc.exports=function(t,e,n,r){let s=[se.COLORTYPE_COLOR_ALPHA,se.COLORTYPE_ALPHA].indexOf(r.colorType)!==-1;if(r.colorType===r.inputColorType){let h=(function(){let y=new ArrayBuffer(2);return new DataView(y).setInt16(0,256,!0),new Int16Array(y)[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=se.COLORTYPE_TO_BPP_MAP[r.inputColorType];a===4&&!r.inputHasAlpha&&(a=3);let l=se.COLORTYPE_TO_BPP_MAP[r.colorType];r.bitDepth===16&&(o=65535,l*=2);let c=Buffer.alloc(e*n*l),u=0,p=0,g=r.bgColor||{};g.red===void 0&&(g.red=o),g.green===void 0&&(g.green=o),g.blue===void 0&&(g.blue=o);function f(){let h,y,_,w=o;switch(r.inputColorType){case se.COLORTYPE_COLOR_ALPHA:w=i[u+3],h=i[u],y=i[u+1],_=i[u+2];break;case se.COLORTYPE_COLOR:h=i[u],y=i[u+1],_=i[u+2];break;case se.COLORTYPE_ALPHA:w=i[u+1],h=i[u],y=h,_=h;break;case se.COLORTYPE_GRAYSCALE:h=i[u],y=h,_=h;break;default:throw new Error("input color type:"+r.inputColorType+" is not supported at present")}return r.inputHasAlpha&&(s||(w/=o,h=Math.min(Math.max(Math.round((1-w)*g.red+w*h),0),o),y=Math.min(Math.max(Math.round((1-w)*g.green+w*y),0),o),_=Math.min(Math.max(Math.round((1-w)*g.blue+w*_),0),o))),{red:h,green:y,blue:_,alpha:w}}for(let h=0;h<n;h++)for(let y=0;y<e;y++){let _=f(i,u);switch(r.colorType){case se.COLORTYPE_COLOR_ALPHA:case se.COLORTYPE_COLOR:r.bitDepth===8?(c[p]=_.red,c[p+1]=_.green,c[p+2]=_.blue,s&&(c[p+3]=_.alpha)):(c.writeUInt16BE(_.red,p),c.writeUInt16BE(_.green,p+2),c.writeUInt16BE(_.blue,p+4),s&&c.writeUInt16BE(_.alpha,p+6));break;case se.COLORTYPE_ALPHA:case se.COLORTYPE_GRAYSCALE:{let w=(_.red+_.green+_.blue)/3;r.bitDepth===8?(c[p]=w,s&&(c[p+1]=_.alpha)):(c.writeUInt16BE(w,p),s&&c.writeUInt16BE(_.alpha,p+2));break}default:throw new Error("unrecognised color Type "+r.colorType)}u+=a,p+=l}return c}});var kc=S((xw,Tc)=>{"use strict";var bc=ci();function tm(t,e,n,r,s){for(let i=0;i<n;i++)r[s+i]=t[e+i]}function nm(t,e,n){let r=0,s=e+n;for(let i=e;i<s;i++)r+=Math.abs(t[i]);return r}function rm(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 sm(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 im(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 om(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 am(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 lm(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 cm(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]-bc(a,l,c);r[s+o]=u}}function um(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]-bc(o,a,l);s+=Math.abs(c)}return s}var dm={0:tm,1:rm,2:im,3:am,4:cm},fm={0:nm,1:sm,2:om,3:lm,4:um};Tc.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 p=0;p<n;p++){if(i.length>1){let g=1/0;for(let f=0;f<i.length;f++){let h=fm[i[f]](t,l,o,s);h<g&&(u=i[f],g=h)}}c[a]=u,a++,dm[u](t,l,o,c,a,s),a+=o,l+=o}return c}});var _i=S((Rw,vc)=>{"use strict";var H=Ut(),pm=pi(),hm=Ec(),gm=kc(),mm=C("zlib"),qe=vc.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||mm.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")};qe.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};qe.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};qe.prototype.filterData=function(t,e,n){let r=hm(t,e,n,this._options),s=H.COLORTYPE_TO_BPP_MAP[this._options.colorType];return gm(r,e,n,this._options,s)};qe.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(pm.crc32(r.slice(4,r.length-4)),r.length-4),r};qe.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)};qe.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)};qe.prototype.packIDAT=function(t){return this._packChunk(H.TYPE_IDAT,t)};qe.prototype.packIEND=function(){return this._packChunk(H.TYPE_IEND,null)}});var Rc=S((Pw,xc)=>{"use strict";var ym=C("util"),Cc=C("stream"),_m=Ut(),wm=_i(),Ic=xc.exports=function(t){Cc.call(this);let e=t||{};this._packer=new wm(e),this._deflate=this._packer.createDeflate(),this.readable=!0};ym.inherits(Ic,Cc);Ic.prototype.pack=function(t,e,n,r){this.emit("data",Buffer.from(_m.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 Bc=S((pn,Lc)=>{"use strict";var Pc=C("assert").ok,Ft=C("zlib"),Sm=C("util"),Ac=C("buffer").kMaxLength;function st(t){if(!(this instanceof st))return new st(t);t&&t.chunkSize<Ft.Z_MIN_CHUNK&&(t.chunkSize=Ft.Z_MIN_CHUNK),Ft.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 Em(t){return new st(t)}function Oc(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}st.prototype._processChunk=function(t,e,n){if(typeof n=="function")return Ft.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 p(h,y){if(r._hadError)return;let _=i-y;if(Pc(_>=0,"have should not go down"),_>0){let w=r._buffer.slice(r._offset,r._offset+_);if(r._offset+=_,w.length>o&&(w=w.slice(0,o)),l.push(w),c+=w.length,o-=w.length,o===0)return!1}return(y===0||r._offset>=r._chunkSize)&&(i=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),y===0?(a+=s-h,s=h,!0):!1}Pc(this._handle,"zlib binding closed");let g;do g=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,i),g=g||this._writeState;while(!this._hadError&&p(g[0],g[1]));if(this._hadError)throw u;if(c>=Ac)throw Oc(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Ac.toString(16)+" bytes");let f=Buffer.concat(l,c);return Oc(this),f};Sm.inherits(st,Ft.Inflate);function bm(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=Ft.Z_FINISH),t._processChunk(e,n)}function Nc(t,e){return bm(new st(e),t)}Lc.exports=pn=Nc;pn.Inflate=st;pn.createInflate=Em;pn.inflateSync=Nc});var wi=S((Aw,Dc)=>{"use strict";var Mc=Dc.exports=function(t){this._buffer=t,this._reads=[]};Mc.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Mc.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 Uc=S($c=>{"use strict";var Tm=wi(),km=ui();$c.process=function(t,e){let n=[],r=new Tm(t);return new km(e,{read:r.read.bind(r),write:function(i){n.push(i)},complete:function(){}}).start(),r.process(),Buffer.concat(n)}});var Kc=S((Nw,qc)=>{"use strict";var Fc=!0,jc=C("zlib"),vm=Bc();jc.deflateSync||(Fc=!1);var Cm=wi(),Im=Uc(),xm=hi(),Rm=gi(),Pm=mi();qc.exports=function(t,e){if(!Fc)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(E){n=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 p=[];function g(E){p.push(E)}let f=new Cm(t);if(new xm(e,{read:f.read.bind(f),error:r,metadata:i,gamma:u,palette:a,transColor:o,inflateData:g,simpleTransparency:l}).start(),f.process(),n)throw n;let y=Buffer.concat(p);p.length=0;let _;if(s.interlace)_=jc.inflateSync(y);else{let T=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;_=vm(y,{chunkSize:T,maxLength:T})}if(y=null,!_||!_.length)throw new Error("bad png - invalid inflate data response");let w=Im.process(_,s);y=null;let x=Rm.dataToBitMap(w,s);w=null;let A=Pm(x,s);return s.data=A,s.gamma=c||0,s}});var Gc=S((Lw,Vc)=>{"use strict";var Wc=!0,Hc=C("zlib");Hc.deflateSync||(Wc=!1);var Am=Ut(),Om=_i();Vc.exports=function(t,e){if(!Wc)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 Om(n),s=[];s.push(Buffer.from(Am.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=Hc.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 Yc=S(Si=>{"use strict";var Nm=Kc(),Lm=Gc();Si.read=function(t,e){return Nm(t,e||{})};Si.write=function(t,e){return Lm(t,e)}});var Qc=S(Jc=>{"use strict";var Bm=C("util"),zc=C("stream"),Mm=wc(),Dm=Rc(),$m=Yc(),V=Jc.PNG=function(t){zc.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 Mm(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 Dm(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"))};Bm.inherits(V,zc);V.sync=$m;V.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)};V.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};V.prototype.write=function(t){return this._parser.write(t),!0};V.prototype.end=function(t){this._parser.end(t)};V.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};V.prototype._gamma=function(t){this.gamma=t};V.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};V.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)};V.prototype.bitblt=function(t,e,n,r,s,i,o){return V.bitblt(this,t,e,n,r,s,i,o),this};V.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}};V.prototype.adjustGamma=function(){V.adjustGamma(this)}});var hn=S(it=>{function Zc(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("")}}it.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:Zc(e.color.dark||"#000000ff"),light:Zc(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};it.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};it.getImageWidth=function(e,n){let r=it.getScale(e,n);return Math.floor((e+n.margin*2)*r)};it.qrToImageData=function(e,n,r){let s=n.modules.size,i=n.modules.data,o=it.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 p=0;p<a;p++){let g=(u*a+p)*4,f=r.color.light;if(u>=l&&p>=l&&u<a-l&&p<a-l){let h=Math.floor((u-l)/o),y=Math.floor((p-l)/o);f=c[i[h*s+y]?1:0]}e[g++]=f.r,e[g++]=f.g,e[g++]=f.b,e[g]=f.a}}});var Xc=S(_e=>{var Um=C("fs"),Fm=Qc().PNG,Ei=hn();_e.render=function(e,n){let r=Ei.getOptions(n),s=r.rendererOpts,i=Ei.getImageWidth(e.modules.size,r);s.width=i,s.height=i;let o=new Fm(s);return Ei.qrToImageData(o.data,e,r),o};_e.renderToDataURL=function(e,n,r){typeof r>"u"&&(r=n,n=void 0),_e.renderToBuffer(e,n,function(s,i){s&&r(s);let o="data:image/png;base64,";o+=i.toString("base64"),r(null,o)})};_e.renderToBuffer=function(e,n,r){typeof r>"u"&&(r=n,n=void 0);let s=_e.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()};_e.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=Um.createWriteStream(e);a.on("error",o),a.on("close",o),_e.renderToFileStream(a,n,r)};_e.renderToFileStream=function(e,n,r){_e.render(n,r).pack().pipe(e)}});var eu=S(Sr=>{var jm=hn(),qm={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Km={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Wm(t,e,n){return t&&e?n.BB:t&&!e?n.BW:!t&&e?n.WB:n.WW}Sr.render=function(t,e,n){let r=jm.getOptions(e),s=qm;(r.color.dark.hex==="#ffffff"||r.color.light.hex==="#000000")&&(s=Km);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+`
|
|
61
|
+
`);let c=Array(r.margin+1).join(s.WW);a+=l;for(let u=0;u<i;u+=2){a+=c;for(let p=0;p<i;p++){let g=o[u*i+p],f=o[(u+1)*i+p];a+=Wm(g,f,s)}a+=c+`
|
|
62
|
+
`}return a+=l.slice(0,-1),typeof n=="function"&&n(null,a),a};Sr.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=C("fs"),o=Sr.render(n,r);i.writeFile(e,o,s)}});var nu=S(tu=>{tu.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+`
|
|
62
63
|
`;for(let u=0;u<r;++u){a+=o;for(let p=0;p<r;p++)a+=s[u*r+p]?i:o;a+=c+`
|
|
63
64
|
`}return a+=l+`
|
|
64
|
-
`,typeof n=="function"&&n(null,a),a}});var
|
|
65
|
-
`+o,p=o;for(let g=-1;g<r+1;g+=2){for(let f=-1;f<r;f++)p+=c[
|
|
66
|
-
`;return typeof r=="function"&&r(null,g),g}});var
|
|
67
|
-
`)}var
|
|
65
|
+
`,typeof n=="function"&&n(null,a),a}});var ou=S(iu=>{var Hm="\x1B[47m",Vm="\x1B[40m",bi="\x1B[37m",Ti="\x1B[30m",ot="\x1B[0m",Gm=Hm+Ti,Ym=Vm+bi,zm=function(t,e,n){return{"00":ot+" "+t,"01":ot+e+"\u2584"+t,"02":ot+n+"\u2584"+t,10:ot+e+"\u2580"+t,11:" ",12:"\u2584",20:ot+n+"\u2580"+t,21:"\u2580",22:"\u2588"}},ru=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"},su=function(t,e,n,r){return ru(t,e,n,r)+ru(t,e,n,r+1)};iu.render=function(t,e,n){let r=t.modules.size,s=t.modules.data,i=!!(e&&e.inverse),o=e&&e.inverse?Ym:Gm,c=zm(o,i?Ti:bi,i?bi:Ti),u=ot+`
|
|
66
|
+
`+o,p=o;for(let g=-1;g<r+1;g+=2){for(let f=-1;f<r;f++)p+=c[su(s,r,f,g)];p+=c[su(s,r,r,g)]+u}return p+=ot,typeof n=="function"&&n(null,p),p}});var lu=S(au=>{var Jm=nu(),Qm=ou();au.render=function(t,e,n){return e&&e.small?Qm.render(t,e,n):Jm.render(t,e,n)}});var vi=S(uu=>{var Zm=hn();function cu(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function ki(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function Xm(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?ki("M",l+n,.5+c+n):ki("m",s,0),s=0,i=!1),l+1<e&&t[a+1]||(r+=ki("h",o),o=0)):s++}return r}uu.render=function(e,n,r){let s=Zm.getOptions(n),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,l=s.color.light.a?"<path "+cu(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",c="<path "+cu(s.color.dark,"stroke")+' d="'+Xm(o,i,s.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
|
|
67
|
+
`;return typeof r=="function"&&r(null,g),g}});var du=S(Er=>{var ey=vi();Er.render=ey.render;Er.renderToFile=function(e,n,r,s){typeof s>"u"&&(s=r,r=void 0);let i=C("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">'+Er.render(n,r);i.writeFile(e,a,s)}});var fu=S(br=>{var Ci=hn();function ty(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 ny(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}br.render=function(e,n,r){let s=r,i=n;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),n||(i=ny()),s=Ci.getOptions(s);let o=Ci.getImageWidth(e.modules.size,s),a=i.getContext("2d"),l=a.createImageData(o,o);return Ci.qrToImageData(l.data,e,s),ty(a,i,o),a.putImageData(l,0,0),i};br.renderToDataURL=function(e,n,r){let s=r;typeof s>"u"&&(!n||!n.getContext)&&(s=n,n=void 0),s||(s={});let i=br.render(e,n,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var hu=S(gn=>{var ry=Fs(),Ii=ii(),pu=fu(),sy=vi();function xi(t,e,n,r,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!ry())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=Ii.create(n,r);l(t(u,e,r))}catch(u){c(u)}})}try{let l=Ii.create(n,r);s(null,t(l,e,r))}catch(l){s(l)}}gn.create=Ii.create;gn.toCanvas=xi.bind(null,pu.render);gn.toDataURL=xi.bind(null,pu.renderToDataURL);gn.toString=xi.bind(null,function(t,e,n){return sy.render(t,n)})});var _u=S(Ke=>{var gu=Fs(),Ri=ii(),iy=Xc(),mu=eu(),oy=lu(),yu=du();function mn(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(gu())e=n||{},n=null;else throw new Error("Callback required as last argument");return{opts:e,cb:n}}function ay(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Tr(t){switch(t){case"svg":return yu;case"txt":case"utf8":return mu;default:return iy}}function ly(t){switch(t){case"svg":return yu;case"terminal":return oy;default:return mu}}function yn(t,e,n){if(!n.cb)return new Promise(function(r,s){try{let i=Ri.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=Ri.create(e,n.opts);return t(r,n.opts,n.cb)}catch(r){n.cb(r)}}Ke.create=Ri.create;Ke.toCanvas=hu().toCanvas;Ke.toString=function(e,n,r){let s=mn(e,n,r),i=s.opts?s.opts.type:void 0,o=ly(i);return yn(o.render,e,s)};Ke.toDataURL=function(e,n,r){let s=mn(e,n,r),i=Tr(s.opts.type);return yn(i.renderToDataURL,e,s)};Ke.toBuffer=function(e,n,r){let s=mn(e,n,r),i=Tr(s.opts.type);return yn(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&&!gu())throw new Error("Too few arguments provided");let i=mn(n,r,s),o=i.opts.type||ay(e),l=Tr(o).renderToFile.bind(null,e);return yn(l,n,i)};Ke.toFileStream=function(e,n,r){if(arguments.length<2)throw new Error("Too few arguments provided");let s=mn(n,r,e.emit.bind(e,"error")),o=Tr("png").renderToFileStream.bind(null,e);yn(o,n,s)}});var Su=S((Yw,wu)=>{wu.exports=_u()});dt();ft();import Ey from"crypto";import{execFile as Mu}from"child_process";var If=lt(Vo(),1),xf=lt(Kr(),1),Rf=lt(Vr(),1),na=lt(Ln(),1),Pf=lt(ta(),1);var St=na.default;dt();ft();Xe();At();Ct();le();var Kh=new Set(["session_history_response","sessions_response","projects_response"]);function Wh(){return!0}function ne(t){if(d.ws&&d.ws.readyState===St.OPEN){let e=t;if(d.sharedSecret&&Ze.has(t.type)&&t.payload){let{payload:r,...s}=t,i={...r,_ts:Date.now()},o=Wh()&&Kh.has(t.type);e={...s,encrypted:Ja(i,d.sharedSecret,o)}}else if(!d.sharedSecret&&Ze.has(t.type)&&t.payload)return console.warn(m.yellow(` Dropped ${t.type}: no encryption key available`)),!1;let n=JSON.stringify({...e,version:z});return d.ws.send(n),!0}else return console.error(m.red(` Message dropped (not connected): ${t.type}`)),!1}function cr(t=1e4){return new Promise(e=>{if(d.ws&&d.ws.readyState===St.OPEN){e(!0);return}let n=setInterval(()=>{d.ws&&d.ws.readyState===St.OPEN&&(clearInterval(n),clearTimeout(r),e(!0))},100),r=setTimeout(()=>{clearInterval(n),e(!1)},t)})}function Us(t=1e4){return new Promise(e=>{let n=setTimeout(()=>{d.registeredResolve=null,e(!1)},t);d.registeredResolve=()=>{clearTimeout(n),e(!0)}})}var Hh=Or*2.5;function Vh(){dl(),d.lastMessageAt=Date.now(),d.heartbeatTimer=setInterval(()=>{if(d.lastMessageAt&&Date.now()-d.lastMessageAt>Hh){console.log(m.yellow(" Relay unresponsive \u2014 forcing reconnect")),d.ws?.close();return}ne({type:"heartbeat",sessionId:null,timestamp:Date.now(),payload:{activeSessions:ke().getActiveSessions()}})},Or)}function dl(){d.heartbeatTimer&&(clearInterval(d.heartbeatTimer),d.heartbeatTimer=null)}function et(){if(d.shuttingDown)return;d.machine.state==="disconnected"&&d.machine.transition({type:"CONNECT"});let t=Ar,e={};d.deviceToken&&(e.Authorization=`Bearer ${d.deviceToken}`),d.ws=new St(t,{headers:e});let n=!1;d.ws.on("open",()=>{d.machine.transition({type:"WS_OPEN"}),ne({type:"register",payload:{role:"desktop",deviceId:d.deviceId,projectName:Hn(),projects:d.projects.map(r=>({name:r.name})),publicKey:Y(me(d.ownKeyPair.publicKey))}}),Vh()}),d.ws.on("message",async r=>{d.lastMessageAt=Date.now();let s=await Ms(r.toString(),ne,d.projects,ke());s.projects.length>0&&(d.projects=s.projects),d.disconnectedByRemote&&d.ws?.readyState===St.OPEN&&d.ws.close()}),d.ws.on("close",(r,s)=>{if(dl(),d.shuttingDown)return;let i=s?.toString()||"";if(console.log(m.dim(` WS close: code=${r} reason="${i}" machine=${d.machine.state}`)),d.inSetupMode){setTimeout(()=>et(),1e3);return}if(d.machine.state==="disconnected"){d.enterSetupMode?.();return}d.machine.transition({type:"WS_CLOSE",networkError:n})==="reconnecting"&&(console.log(m.yellow(" Disconnected from relay")),Gh())}),d.ws.on("error",r=>{if(d.shuttingDown)return;let s=r.message||"";(s.includes("ENOTFOUND")||s.includes("ETIMEDOUT")||s.includes("ENETUNREACH")||s.includes("ECONNREFUSED")||s.includes("EAI_AGAIN"))&&(n=!0),console.error(m.red(` Connection error: ${r.message}`))})}function Gh(){let t=d.reconnectDelay;console.log(m.dim(` Reconnecting in ${t/1e3}s...`)),setTimeout(()=>{d.machine.context.reconnectDelay=$s(d.machine.context.reconnectDelay,zi),d.machine.transition({type:"RECONNECT_TIMER"}),et()},t)}dt();var ku=lt(Su(),1);ft();import{createInterface as uy}from"readline";At();le();le();ft();var Pi=bt;function Eu(t){Pi=t}async function bu(t,e){let n=await fetch(`${Pi}/v1/pairing/request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({publicKey:t,deviceId:e,version:z}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new Error(`Pairing request failed: ${n.status} ${n.statusText}`);return n.json()}async function Tu(t,e){let n=await fetch(`${Pi}/v1/pairing/status?code=${encodeURIComponent(t)}&token=${encodeURIComponent(e)}`,{signal:AbortSignal.timeout(1e4)});if(!n.ok)throw new Error(`Pairing status check failed: ${n.status} ${n.statusText}`);return n.json()}Xe();ae();Qt();function cy(t){let e=ku.default.create(t,{errorCorrectionLevel:"M"}),n=e.modules.size,r=e.modules.data,s=(l,c)=>l>=0&&l<n&&c>=0&&c<n&&!!r[c*n+l],i=(l,c)=>`\x1B[${l?"30":"37"};${c?"40":"47"}m\u2580\x1B[0m`,o=[],a=1;for(let l=-a;l<n+a;l+=2){let c="";for(let u=-a;u<n+a;u++)c+=i(s(u,l),s(u,l+1));o.push(c)}return o.join(`
|
|
68
|
+
`)}var Ai=M("pairing");function vu(t){return new Promise(e=>{if(!process.stdin.isTTY){let s=uy({input:process.stdin,output:process.stdout});s.question(t,i=>{s.close(),e(i.trim())});return}process.stdout.write(t),process.stdin.removeAllListeners("data"),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8");let n="",r=s=>{let i=s.charCodeAt(0);s==="\r"||s===`
|
|
68
69
|
`?(process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",r),process.stdout.write(`
|
|
69
70
|
`),e(n.trim())):i===127||i===8?n.length>0&&(n=n.slice(0,-1),process.stdout.write("\b \b")):i===3?(process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",r),process.stdout.write(`
|
|
70
|
-
`),process.emit("SIGINT")):i>=32&&(n+=s,process.stdout.write("*"))};process.stdin.on("data",r)})}function
|
|
71
|
+
`),process.emit("SIGINT")):i>=32&&(n+=s,process.stdout.write("*"))};process.stdin.on("data",r)})}function dy(t=3e4){return new Promise((e,n)=>{d.verifyCodeResolve=e,setTimeout(()=>{d.verifyCodeResolve===e&&(d.verifyCodeResolve=null,n(new Error("timeout")))},t)})}async function kr(){if(d.inSetupMode)return;let t=!!(d.deviceToken&&d.sharedSecret&&d.peerPublicKey);d.machine.transition({type:"ENTER_SETUP",hasSavedState:t}),await fy()}async function fy(){if(d.deviceToken&&d.sharedSecret&&d.peerPublicKey){console.log(m.yellow(" Attempting to reconnect with saved pairing..."));let e=5,n=2e3;for(let r=1;r<=e;r++){if(await new Promise(i=>setTimeout(i,n)),n=Math.min(n*2,3e4),et(),await cr(15e3)&&await Us(1e4)){console.log(m.green(" Reconnected with saved pairing!"));return}try{d.ws?.close()}catch{}r<e&&console.log(m.dim(` Reconnect attempt ${r}/${e} failed, retrying in ${n/1e3}s...`))}d.machine.transition({type:"SETUP_RECONNECT_FAILED"}),console.log(m.yellow(" Could not reconnect \u2014 starting fresh pairing...")),console.log()}let t=5e3;for(;;){let e=D();e&&e.deviceToken&&(Ai.warn("Clearing deviceToken from config (reason: fresh pairing after reconnect failure)"),U("token_cleared","authentication","warn","Token cleared for fresh pairing after reconnect failure",{reason:"fresh_pairing_after_reconnect_failure"}),delete e.deviceToken,G(e)),d.deviceToken="",Ai.warn("Clearing peerPublicKey and sharedSecret (reason: fresh pairing after reconnect failure)"),U("crypto_state_cleared","crypto","warn","Cleared peerPublicKey and sharedSecret for fresh pairing",{reason:"fresh_pairing"}),d.peerPublicKey=null,d.sharedSecret=null,d.ownKeyPair||(d.ownKeyPair=nn(),Pt({publicKey:Y(me(d.ownKeyPair.publicKey)),secretKey:Y(d.ownKeyPair.secretKey.export({format:"der",type:"pkcs8"}))}));let n=Y(me(d.ownKeyPair.publicKey)),r,s;try{let h=await bu(n,d.deviceId);r=h.pairingCode,s=h.pollToken,t=5e3}catch(h){console.error(m.red(` Pairing request failed: ${h}`)),console.log(m.dim(` Retrying in ${t/1e3}s...`)),await new Promise(y=>setTimeout(y,t)),t=Math.min(t*2,6e4);continue}let i=JSON.stringify({c:r,k:n});console.log(),console.log(" Scan this QR code in your BeachViber App (app.beachviber.com) to pair:"),console.log();try{let y=(await cy(i)).split(`
|
|
71
72
|
`).map(_=>" "+_).join(`
|
|
72
|
-
`);console.log(y)}catch{}console.log(m.bold(" Sign-Up at app.beachviber.com \u2192 Add Computer \u2192 Scan QR Code")),console.log(" Or enter code manually: "+m.cyan(r)),console.log();let o=3e3,a=600*1e3,l=Date.now(),c=!1;for(;Date.now()-l<a;){try{let h=await
|
|
73
|
-
Update detected: v${e} \u2192 v${n}`),t(42))},
|
|
73
|
+
`);console.log(y)}catch{}console.log(m.bold(" Sign-Up at app.beachviber.com \u2192 Add Computer \u2192 Scan QR Code")),console.log(" Or enter code manually: "+m.cyan(r)),console.log();let o=3e3,a=600*1e3,l=Date.now(),c=!1;for(;Date.now()-l<a;){try{let h=await Tu(r,s);if(h.status==="claimed"&&h.deviceToken){d.deviceToken=h.deviceToken;let y=D()||{deviceId:Tt()};y.deviceToken=d.deviceToken,Ai.info(`Saving deviceToken to config (reason: pairing claimed, len=${d.deviceToken.length})`),U("pairing_claimed","pairing","info","Pairing claimed - device token received",{tokenLength:d.deviceToken.length}),G(y),h.claimerPublicKey&&d.ownKeyPair&&(d.peerPublicKey=rn(Rt(h.claimerPublicKey)),d.sharedSecret=ir(d.peerPublicKey,d.ownKeyPair.secretKey)),console.log(m.green(" Phone scanned QR code")+" "+m.green("[claimed]"));break}if(h.status==="expired"){console.log(m.yellow(" Pairing code expired.")),c=!0;break}}catch(h){console.error(m.red(` Poll error: ${h}`))}await new Promise(h=>setTimeout(h,o))}if(c)continue;if(!d.deviceToken){console.log(m.yellow(" Pairing timed out."));continue}if(et(),!await cr()){console.log(m.red(" Failed to connect to relay. Retrying setup..."));continue}if(!await Us()){console.log(m.red(" Registration timed out. Retrying setup..."));continue}let g=3,f=!1;for(let h=1;h<=g;h++){console.log();let y=await vu(m.bold(" Enter the connection password from your BeachViber App: "));if(!y)continue;console.log(m.dim(" Verifying..."));let _=null,w,x=3;for(let A=0;A<x;A++)if(!((!d.ws||d.ws.readyState!==1)&&(console.log(m.dim(" Reconnecting to relay...")),!await cr(5e3)))){w=await xs(y,d.deviceId),ne({type:"verify_code",sessionId:null,timestamp:Date.now(),payload:{code:y,codeHash:w,protocolVersion:3,appVersion:z,capabilities:["wake"],deviceMeta:{name:Hn(),projectCount:d.projects.length,sessionCount:d.projects.reduce((E,T)=>E+T.sessionCount,0)}}});try{_=await dy(15e3);break}catch{A<x-1&&console.log(m.dim(" No response from phone, retrying..."))}}if(!_){console.log(m.yellow(" Phone did not respond. Check your webapp connection and try again."));continue}if(_.success){if(typeof _.appVersion=="string"&&(d.peerAppVersion=_.appVersion),Array.isArray(_.capabilities)&&(d.peerCapabilities=_.capabilities),!d.sharedSecret){console.log(m.red(" Key exchange failed \u2014 shared secret was not established during pairing claim.")),console.log(m.red(" Ensure your BeachViber App is up to date (protocol v3 required)."));break}d.machine.transition({type:"PAIRED"}),U("pairing_completed","pairing","info","Pairing completed - end-to-end encryption active",{});let A=Y(me(d.peerPublicKey));if(Pt({publicKey:Y(me(d.ownKeyPair.publicKey)),secretKey:Y(d.ownKeyPair.secretKey.export({format:"der",type:"pkcs8"})),peerPublicKey:A}),w){let E=D();E&&(E.wakePasswordHash=w,G(E));let T=Xt();d.wakeExpiresAt=Date.now()+T*36e5,Ae(d.wakeExpiresAt),d.wakeTimer=setTimeout(()=>{Promise.resolve().then(()=>(Xe(),lr)).then(({transitionToSleep:k})=>{k("timer_expired",ne)})},T*36e5)}console.log(m.green(" Paired with BeachViber App".padEnd(50))+m.green("[encrypted]")),w&&console.log(m.green(" Wake password set \u2014 awake session started")),console.log(),console.log(m.bold.green(" \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510")),console.log(m.bold.green(" \u2502 \u{1F512} End-to-end encryption active \u2502")),console.log(m.bold.green(" \u2502 \u2502")),console.log(m.bold.green(" \u2502")+m.dim(" All messages between this device and your ")+m.bold.green("\u2502")),console.log(m.bold.green(" \u2502")+m.dim(" phone are encrypted. No one \u2014 not even the ")+m.bold.green("\u2502")),console.log(m.bold.green(" \u2502")+m.dim(" relay server \u2014 can read them. ")+m.bold.green("\u2502")),console.log(m.bold.green(" \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")),console.log(),await Ds(ne),f=!0;break}h<g?console.log(m.red(" Password didn't match. Please try again.")):console.log(m.red(" Password didn't match after 3 attempts. Restarting setup..."))}if(f)return}}var at=!1;function Cu(){if(at||d.wakeState!=="sleeping"||!fe()||!process.stdin.isTTY)return;at=!0,console.log(m.dim(" Type your connection password to unlock, or unlock from the app."));let{wakeLockout:t}=d,e=()=>{if(t.lockedUntil){if(Date.now()<t.lockedUntil){let n=Math.ceil((t.lockedUntil-Date.now())/6e4);console.log(m.red(` Locked out. Try again in ${n} minute${n!==1?"s":""}.`));let r=t.lockedUntil-Date.now();setTimeout(()=>{d.wakeState==="sleeping"?e():at=!1},r+1e3);return}t.failedAttempts=0,t.lockedUntil=null}vu(m.dim(" Password: ")).then(async n=>{if(d.wakeState!=="sleeping"){at=!1;return}if(!n){e();return}let r=D();if(!r?.wakePasswordHash){at=!1;return}let s=await xs(n,d.deviceId);if(n="",or(s,r.wakePasswordHash)){let i=Xt(),o=i*60*60*1e3,a=Date.now()+o;d.machine.state==="paired_sleeping"&&d.machine.transition({type:"WAKE"}),d.wakeExpiresAt=a,Ae(a),t.failedAttempts=0,t.lockedUntil=null,d.wakeTimer&&clearTimeout(d.wakeTimer),d.wakeTimer=setTimeout(()=>{Promise.resolve().then(()=>(Xe(),lr)).then(({transitionToSleep:c})=>{c("timer_expired",ne)})},o);let l=new Date().toLocaleTimeString();Me(["UNLOCKED",`Unlocked for ${i} hours.`],c=>m.green(c)),console.log(m.dim(` ${l}`)),console.log(),ne({type:"wake_ack",sessionId:null,timestamp:Date.now(),payload:{success:!0,expiresAt:a,duration:i}}),at=!1}else{t.failedAttempts++;let i=t.failedAttempts;if(i>=10){t.lockedUntil=Date.now()+1800*1e3,console.log(m.red(" Too many failed attempts \u2014 locked out for 30 minutes."));let a=t.lockedUntil-Date.now();setTimeout(()=>{d.wakeState==="sleeping"?e():at=!1},a+1e3);return}let o=10-i;if(console.log(m.red(` Wrong password. ${o} attempt${o!==1?"s":""} remaining.`)),i>=6){let a=Math.pow(2,i-5)*1e3;await new Promise(l=>setTimeout(l,a))}e()}})};e()}Xe();jn();le();At();Ct();ae();Qt();As();Is();import{execFileSync as py}from"child_process";var Iu="2.0.0";function xu(t){let e=t.trim().match(/^(\d+)\.(\d+)\.(\d+)/);return e?{raw:e[0],major:parseInt(e[1],10),minor:parseInt(e[2],10),patch:parseInt(e[3],10)}:null}function hy(t,e){return t.major!==e.major?t.major<e.major?-1:1:t.minor!==e.minor?t.minor<e.minor?-1:1:t.patch!==e.patch?t.patch<e.patch?-1:1:0}function Ru(){let t=xu(Iu),e;try{e=py("claude",["--version"],{encoding:"utf-8",timeout:5e3,shell:process.platform==="win32",env:{...process.env,CLAUDECODE:""}}).trim()}catch(r){let s=r.message||String(r);return s.includes("ENOENT")?{ok:!1,installed:null,required:t,error:"Claude Code CLI not found. Install it: npm install -g @anthropic-ai/claude-code"}:{ok:!1,installed:null,required:t,error:`Failed to check Claude version: ${s}`}}let n=xu(e);return n?hy(n,t)<0?{ok:!1,installed:n,required:t,error:`Claude Code CLI ${n.raw} is too old. BeachViber requires ${Iu}+ for remote tool approvals. Update with: claude update`}:{ok:!0,installed:n,required:t}:{ok:!1,installed:null,required:t,error:`Could not parse Claude version from: "${e}"`}}import{readFileSync as gy}from"fs";import{dirname as my,join as yy}from"path";import{fileURLToPath as _y}from"url";var wy=1e4,Sy=yy(my(_y(import.meta.url)),"..","package.json"),_n=null;function Pu(){try{let t=gy(Sy,"utf-8");return JSON.parse(t).version}catch{return null}}function Au(t){if(!process.env.BEACHVIBER_MANAGED)return;let e=Pu();if(!e){console.log(" Updates disabled (could not read package.json)");return}console.log(` Updates polling (v${e})`),_n=setInterval(()=>{let n=Pu();n&&n!==e&&(console.log(`
|
|
74
|
+
Update detected: v${e} \u2192 v${n}`),t(42))},wy),_n.unref()}function Ou(){_n&&(clearInterval(_n),_n=null)}ys();var Du=process.argv.slice(2),Nu=Du.indexOf("--profile");if(Nu!==-1){let t=Du[Nu+1];(!t||t.startsWith("--"))&&(console.error("Error: --profile requires a name argument"),process.exit(1));try{_a(t)}catch(e){console.error(`Error: ${e.message}`),process.exit(1)}}la(W(),Q());ma(W(),Q());var Lu=D()?.logLevel;Lu&&ca(Lu);(process.argv.includes("--help")||process.argv.includes("-h"))&&(console.log(`
|
|
74
75
|
${m.bold("BeachViber Desktop")} v${z}
|
|
75
76
|
|
|
76
77
|
${m.bold("Usage:")} beachviber [options]
|
|
@@ -81,6 +82,6 @@ Minimum version required to store current data is: `+i+`.
|
|
|
81
82
|
--soft-reset Clear pairing state and keys, keep API/relay URLs
|
|
82
83
|
-v, --version Show version
|
|
83
84
|
-h, --help Show this help
|
|
84
|
-
`),process.exit(0));(process.argv.includes("--version")||process.argv.includes("-v"))&&(console.log(z),process.exit(0));if(process.argv.includes("--reset")){try{let s=await
|
|
85
|
-
Shutting down...`)),
|
|
86
|
-
[${t}] Reset via IPC \u2014 re-entering setup mode...`)),
|
|
85
|
+
`),process.exit(0));(process.argv.includes("--version")||process.argv.includes("-v"))&&(console.log(z),process.exit(0));if(process.argv.includes("--reset")){try{let s=await ms({type:"reset"});s.ok&&(console.log(m.green(` ${s.message}`)),process.exit(0))}catch{}let t=Zt(),e=t?`profile "${t}"`:"default profile",n=`default${Q()}`;try{console.log(`[reset] Removing keychain secret for account "${n}"`),rr(n)}catch{}let r=as("--reset CLI flag");console.log(r?m.green(` Settings reset for ${e}. Config file and keys removed.`):m.yellow(` No config found for ${e}. Nothing to reset.`)),process.exit(0)}if(process.argv.includes("--soft-reset")){try{let s=await ms({type:"soft-reset"});s.ok&&(console.log(m.green(` ${s.message}`)),process.exit(0))}catch{}let t=Zt(),e=t?`profile "${t}"`:"default profile",n=`default${Q()}`;try{rr(n)}catch{}let r=D();if(r){let s={deviceId:Tt(),...r.relayUrl?{relayUrl:r.relayUrl}:{},...r.apiUrl?{apiUrl:r.apiUrl}:{},...r.deviceName?{deviceName:r.deviceName}:{}};G(s),console.log(m.green(` Soft reset for ${e}. Pairing state and keys cleared; URLs preserved.`))}else console.log(m.yellow(` No config found for ${e}. Nothing to reset.`));process.exit(0)}d.enterSetupMode=()=>kr();d.onSleepTransition=()=>Cu();function Oi(t=0){if(!d.shuttingDown){d.shuttingDown=!0,console.log(m.dim(`
|
|
86
|
+
Shutting down...`)),Na(),Ou();try{d.ws?.close()}catch{}d.heartbeatTimer&&(clearInterval(d.heartbeatTimer),d.heartbeatTimer=null);try{for(let e of ke().getAllSessions())e.process?.pid&&e.process.exitCode===null&&(process.platform==="win32"?Mu("taskkill",["/pid",String(e.process.pid),"/T","/F"],()=>{}):e.process.kill())}catch{}setTimeout(()=>process.exit(t),500).unref()}}process.on("SIGINT",()=>Oi());process.on("SIGTERM",()=>Oi());function $u(){let t=el();if(t)try{let e=Ey.createPrivateKey({format:"der",type:"pkcs8",key:Rt(t.secretKey)}),n=rn(Rt(t.publicKey));d.ownKeyPair={publicKey:n,secretKey:e},t.peerPublicKey&&(d.peerPublicKey=rn(Rt(t.peerPublicKey)),d.sharedSecret=ir(d.peerPublicKey,d.ownKeyPair.secretKey))}catch{d.ownKeyPair=nn(),Pt({publicKey:Y(me(d.ownKeyPair.publicKey)),secretKey:Y(d.ownKeyPair.secretKey.export({format:"der",type:"pkcs8"}))})}else d.ownKeyPair=nn(),Pt({publicKey:Y(me(d.ownKeyPair.publicKey)),secretKey:Y(d.ownKeyPair.secretKey.export({format:"der",type:"pkcs8"}))})}async function Bu(t){let e=`default${Q()}`;try{for(let n of ke().getAllSessions())n.process?.pid&&n.process.exitCode===null&&(process.platform==="win32"?Mu("taskkill",["/pid",String(n.process.pid),"/T","/F"],()=>{}):n.process.kill())}catch{}try{d.ws?.close()}catch{}d.heartbeatTimer&&clearInterval(d.heartbeatTimer),d.wakeTimer&&clearTimeout(d.wakeTimer),Ji();try{rr(e)}catch{}if(t==="reset")as("IPC reset command");else{let n=D();if(n){let r={deviceId:Tt(),...n.relayUrl?{relayUrl:n.relayUrl}:{},...n.apiUrl?{apiUrl:n.apiUrl}:{},...n.deviceName?{deviceName:n.deviceName}:{}};G(r),d.deviceId=r.deviceId}}$u(),d.projects=await Et(),console.log(m.yellow(`
|
|
87
|
+
[${t}] Reset via IPC \u2014 re-entering setup mode...`)),kr()}async function by(t){switch(t.type){case"reset":return await Bu("reset"),{ok:!0,message:"Full reset complete. Agent re-entering setup mode."};case"soft-reset":return await Bu("soft-reset"),{ok:!0,message:"Soft reset complete. URLs preserved. Re-entering setup mode."};case"compact_start":{let e=t.sessionId;return typeof e!="string"||!he.test(e)?{ok:!1,message:"Invalid or missing sessionId"}:(ke().notifyCompactStart(e),{ok:!0,message:"Compact start notification sent"})}default:return{ok:!1,message:`Unknown command: ${t.type}`}}}(async()=>{Ps(),setInterval(Ps,30*6e4).unref(),d.projects=await Et();let t=D();if(!t)d.deviceId=Tt(),t={deviceId:d.deviceId,relayUrl:Wn,apiUrl:bt},G(t);else{d.deviceId=t.deviceId;let l=!1;t.relayUrl||(t.relayUrl=Wn,l=!0),t.apiUrl||(t.apiUrl=bt,l=!0),l&&G(t)}Yi(process.env.RELAY_URL||t?.relayUrl||Wn),Eu(process.env.API_URL||t?.apiUrl||bt),d.deviceToken=process.env.BV_DEVICE_TOKEN||t?.deviceToken||"",$u();let e=t?.wakeExpiresAt;if(e&&e>Date.now()){d.wakeExpiresAt=e;let l=e-Date.now();d.wakeTimer=setTimeout(()=>{Promise.resolve().then(()=>(Xe(),lr)).then(({transitionToSleep:c})=>{c("timer_expired",ne)})},l)}else e&&Ae(null);let n=!!(d.deviceToken&&d.sharedSecret&&d.peerPublicKey);console.log(),console.log(m.bold(" BeachViber Agent")+m.dim(` v${z}`)),Zt()&&console.log(m.dim(" Profile ")+m.bold(Zt())),console.log();let r=d.projects.reduce((l,c)=>l+c.sessionCount,0);console.log(m.dim(" Projects ")+m.bold(String(d.projects.length))+m.dim(` (${r} sessions)`));for(let l of d.projects){let c=l.git.branch!=="unknown"?m.dim(` (${l.git.branch})`):"",u=m.dim(` \u2014 ${l.sessionCount} sessions`);console.log(m.dim(" ")+l.name+c+u)}let s=Ru();s.installed&&console.log(m.dim(" Claude ")+m.bold(`v${s.installed.raw}`)),s.ok||(console.log(),console.log(m.red(` ERROR: ${s.error}`)),console.log(),process.exit(1));let i=za(),o=i?.includes("file")?m.yellow:m.green;if(console.log(m.dim(" Secrets ")+(i?o(i):m.yellow("plaintext (no OS store available)"))),fe()&&!d.wakeExpiresAt){let l=new Date().toLocaleTimeString();Me(["LOCKED","Remote access is locked.","Unlock from app or terminal."],c=>m.yellow(c)),console.log(m.dim(` ${l}`)),console.log()}else if(fe()&&d.wakeExpiresAt){let l=Math.ceil((d.wakeExpiresAt-Date.now())/36e5),c=new Date().toLocaleTimeString();Me(["UNLOCKED",`Unlocked for ~${l} more hour${l!==1?"s":""}.`],u=>m.green(u)),console.log(m.dim(` ${c}`)),console.log()}n?console.log(m.dim(" State ")+m.green("Saved pairing found \u2014 reconnecting...")):d.deviceToken?console.log(m.dim(" State ")+m.yellow("Incomplete pairing \u2014 re-entering setup")):console.log(m.dim(" State ")+m.yellow("New \u2014 pairing required")),console.log(),qa().setPhoneSendFn(ne),Oa(by),Au(Oi),n?(console.log(m.green(" Reconnecting with saved pairing...".padEnd(50))+m.green("[encrypted]")),console.log(),et()):kr()})().catch(t=>{console.error(m.red(` Fatal error: ${t}`)),process.exit(1)});
|