9remote 2.0.58 → 2.0.59
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/cli.cjs +2 -2
- package/dist/ptyDaemon.cjs +1 -1
- package/dist/server.cjs +4 -4
- package/dist/ui/assets/{index-CrI5NVH8.js → index-EcwsBC8r.js} +3130 -3130
- package/dist/ui/index.html +1 -1
- package/package.json +1 -1
package/dist/server.cjs
CHANGED
|
@@ -88,7 +88,7 @@ WantedBy=default.target
|
|
|
88
88
|
|
|
89
89
|
`),Il&&e.write(`data: ${JSON.stringify({type:"updateAvailable",...Il})}
|
|
90
90
|
|
|
91
|
-
`),Ml.add(e),r.on("close",()=>Ml.delete(e))}function nS(r,e){ee(e,{...dn,...Ar,desktopEnabled:jt,remoteAvailable:Eh})}async function iS(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Gt(),Ii)),n=await t(r,e);n&&(hn(n),ee(e))}function sS(r,e){ee(e),hn({step:Xn.PREPARING,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null}),$n("restart-tunnel")}function oS(r,e){ee(e),hn({step:Xn.PREPARING,stepDesc:""}),$n("start-tunnel")}function aS(r,e){ee(e),hn({step:Xn.STOPPED,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null}),$n("stop-tunnel")}function cS(r,e){ee(e),hn({step:Xn.STOPPED,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null}),$n("shutdown")}function lS(r,e){ee(e),$n("update")}function uS(r,e){ee(e,{connections:[...hi.values()]})}function pS(r,e){let t=new URL(r.url,"http://localhost"),n=parseInt(t.searchParams.get("lines")||Rp,10);ee(e,{logs:Hv(Number.isFinite(n)?n:Rp)})}async function fS(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Gt(),Ii)),n=await t(r,e);if(!n)return;let i=!!n.enabled;if(i&&(!Ar.screenRecording||!Ar.accessibility)){ee(e,{ok:!1,enabled:jt,reason:"permissions_required"});return}let s=Es();jt=i,Sh(),St("permissions",{...Ar,desktopEnabled:jt}),Es()!==s&&Th?.(),ee(e,{ok:!0,enabled:jt})}function dS(r,e){ee(e,Ar)}async function hS(r,e){let t=await hh();ee(e,{enabled:t})}async function mS(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Gt(),Ii)),n=await t(r,e);if(!n)return;let i=await Dw(!!n.enabled),s=await hh();St("autostart",{enabled:s}),ee(e,{ok:i,enabled:s})}async function gS(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Gt(),Ii)),n=await t(r,e);if(!n)return;let{type:i}=n;if(process.platform==="darwin"){Ow(i);let s=Date.now(),o=setInterval(async()=>{((await Nl())[i]||Date.now()-s>Nv)&&clearInterval(o)},Iv)}ee(e)}var Hn,qw,wh,dn,jt,Eh,Ar,Ml,hi,Il,Th,Un=Ce(()=>{vt();Li();vt();ys();Pw();mh();Gt();cl();vt();Hn=require("fs"),qw=require("path");vt();gh();wh=(0,qw.join)(oe.STATE,"ui-state.json");dn={step:Xn.STOPPED,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null,permanentKey:"",qrUrl:"",latency:null,uptime:null,healthCheck:{running:!1,timeoutMs:0,startedAt:null,logs:[]},tunnelHealth:{status:"unknown",checkedAt:null}},jt=!1,Eh=!1,Ar={screenRecording:!1,accessibility:!1},Ml=new Set,hi=new Map;$v(Te);Il=null;Th=null});var Ll,vS=Ce(()=>{bt();Un();Ll=class{constructor(){this.cfg=Z.logging,this.samples=[],this.lastLogTime=Date.now()}now(){return this.cfg.metrics?performance.now():0}record({capture:e,checksum:t,encode:n,total:i,changedTiles:s,totalTiles:o,tileBytes:a,rawBytes:c}){this.cfg.metrics&&(this.samples.push({capture:e,checksum:t,encode:n,total:i,changedTiles:s,totalTiles:o,tileBytes:a,rawBytes:c}),this.samples.length>=this.cfg.metricsEveryFrames&&this._flush())}_flush(){let e=this.samples.length,t=N=>(this.samples.reduce(($,W)=>$+W[N],0)/e).toFixed(1),n=(Date.now()-this.lastLogTime)/1e3,i=(e/n).toFixed(1),s=[],o=0;for(let N of this.samples){for(let $ of N.tileBytes)s.push($);o+=N.tileBytes.reduce(($,W)=>$+W,0)}let a=(o/e/1024).toFixed(1),c=s.length?(s.reduce((N,$)=>N+$,0)/s.length/1024).toFixed(2):"0",u=s.length?(Math.min(...s)/1024).toFixed(2):"0",p=s.length?(Math.max(...s)/1024).toFixed(2):"0",f=this.samples.reduce((N,$)=>N+$.rawBytes,0)/e,m=o/e,y=m>0?(f/m).toFixed(0):"0",_=(this.samples.reduce((N,$)=>N+$.changedTiles,0)/e).toFixed(0),S=this.samples[0]?.totalTiles||0,A=S?(_/S*100).toFixed(1):"0",P=Z.pipeline,L=`[Metrics] ${P.captureLib}+${P.encoder} tile=${P.tileSize} q${P.jpegQuality} scale=${P.outputScale} | fps=${i} | capture=${t("capture")}ms enc=${t("encode")}ms total=${t("total")}ms | tiles=${_}/${S} (${A}%) | data=${a}KB/frame | tileAvg=${c}KB (min ${u}, max ${p}) | compress=${y}x`;Te(L),console.log(L),this.samples=[],this.lastLogTime=Date.now()}}});var _S={};Xr(_S,{TileManager:()=>Ch});var Ts,Bl,xS,Dl,yS,XB,JB,Ch,bS=Ce(()=>{Ts=X(require("fs"),1),Bl=X(require("path"),1),xS=X(require("sharp"),1),Dl=require("child_process"),yS=require("url");bt();Sw();Tw();vS();Kd();XB=(0,yS.fileURLToPath)(__importMetaUrl),JB=Bl.default.dirname(XB),Ch=class{constructor(e){this.robot=e,this.metrics=new Ll,this.tileSize=Z.pipeline.tileSize,this.lastTileChecksums=new Map,this.screenWidth=0,this.screenHeight=0,this.tilesPerRow=0,this.tilesPerColumn=0,this.totalTiles=0,this.frameCount=0,this.tempDir=Bl.default.join(JB,"../../temp"),this.changeThreshold=1,this.scaledWidth=0,this.scaledHeight=0,this.isProcessing=!1,this.sharedScreenCache=null,this.lastCaptureTime=0,this.CACHE_TTL=100,this.dpiScale=1,this.captureWidth=0,this.captureHeight=0,this.scaleFactor=Z.pipeline.outputScale||1,this.compressionQuality=Z.pipeline.jpegQuality,this.activeTileSet=null,this.focusStats={frames:0,scanned:0,changed:0,bytes:0},Ts.default.existsSync(this.tempDir)||Ts.default.mkdirSync(this.tempDir,{recursive:!0}),bw(e),this.initializeScreenDimensions()}initializeScreenDimensions(){try{let{width:e,height:t}=this.robot.getScreenSize();this.screenWidth=e,this.screenHeight=t,this.detectDpiScale(),this.scaledWidth=this.captureWidth,this.scaledHeight=this.captureHeight,this.tilesPerRow=Math.ceil(this.scaledWidth/this.tileSize),this.tilesPerColumn=Math.ceil(this.scaledHeight/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn;let n=100;if(this.totalTiles>n){let i=Math.ceil(Math.sqrt(this.scaledWidth*this.scaledHeight/n));this.tileSize=Math.max(i,120),this.tilesPerRow=Math.ceil(this.scaledWidth/this.tileSize),this.tilesPerColumn=Math.ceil(this.scaledHeight/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn}}catch(e){ve.error("Screen dimensions error:",e),this.screenWidth=1920,this.screenHeight=1080,this.dpiScale=1,this.captureWidth=1920,this.captureHeight=1080,this.scaledWidth=1728,this.scaledHeight=972,this.tileSize=120,this.tilesPerRow=Math.ceil(this.scaledWidth/this.tileSize),this.tilesPerColumn=Math.ceil(this.scaledHeight/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn}}detectDpiScale(){if(process.platform==="darwin"){let e=this.robot.screen.capture(0,0,this.screenWidth,this.screenHeight),n=e.byteWidth/e.bytesPerPixel/this.screenWidth;n>=1.9&&n<=2.1?this.dpiScale=2:this.dpiScale=1}else process.platform==="win32"?this.dpiScale=this._detectDpiScaleWin32():this.dpiScale=1;this.captureWidth=Math.floor(this.screenWidth*this.dpiScale),this.captureHeight=Math.floor(this.screenHeight*this.dpiScale)}_detectDpiScaleWin32(){ve.dpi(`\u{1F50D} [DPI Detection] screenWidth from robot: ${this.screenWidth}x${this.screenHeight}`);try{let e=(0,Dl.execSync)(`powershell -NonInteractive -NoProfile -WindowStyle Hidden -command "try{Get-ItemPropertyValue 'HKCU:\\Control Panel\\Desktop\\WindowMetrics' -Name AppliedDPI}catch{0}"`,{encoding:"utf8",windowsHide:!0}).trim(),t=Number(e);if(ve.dpi(`\u{1F50D} [DPI Detection] Strategy 1 (Registry AppliedDPI): ${t} DPI`),t>=96){let n=t/96;return ve.dpi(`\u2705 [DPI Detection] Using registry scale: ${n}x (${t}/96)`),n}}catch(e){ve.dpi(`\u274C [DPI Detection] Strategy 1 failed: ${e.message}`)}try{let e=(0,Dl.execSync)('powershell -NonInteractive -NoProfile -WindowStyle Hidden -command "(Get-WmiObject -Class Win32_VideoController | Select-Object -First 1).CurrentHorizontalResolution"',{encoding:"utf8",windowsHide:!0}).trim(),t=Number(e);if(ve.dpi(`\u{1F50D} [DPI Detection] Strategy 2 (WMI): physical width = ${t}px`),t>0&&t>this.screenWidth){let n=t/this.screenWidth;return ve.dpi(`\u2705 [DPI Detection] Using WMI scale: ${n}x (${t}/${this.screenWidth})`),n}}catch(e){ve.dpi(`\u274C [DPI Detection] Strategy 2 failed: ${e.message}`)}try{let e=(0,Dl.execSync)(`powershell -NonInteractive -NoProfile -WindowStyle Hidden -command "Add-Type -TypeDefinition 'using System;using System.Runtime.InteropServices;public class Disp{[DllImport(\\"user32\\")]public static extern bool EnumDisplaySettings(string d,int m,ref DEVMODE dm);[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]public struct DEVMODE{[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)]public string dmDeviceName;public short dmSpecVersion,dmDriverVersion,dmSize,dmDriverExtra;public int dmFields;public int dmPositionX,dmPositionY,dmDisplayOrientation,dmDisplayFixedOutput;public short dmColor,dmDuplex,dmYResolution,dmTTOption,dmCollate;[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)]public string dmFormName;public short dmLogPixels;public int dmBitsPerPel,dmPelsWidth,dmPelsHeight,dmDisplayFlags,dmDisplayFrequency;}}'; $dm=New-Object Disp+DEVMODE; $dm.dmSize=[System.Runtime.InteropServices.Marshal]::SizeOf($dm); [Disp]::EnumDisplaySettings($null,-1,[ref]$dm) | Out-Null; Write-Output $dm.dmPelsWidth"`,{encoding:"utf8",windowsHide:!0}).trim(),t=Number(e);if(ve.dpi(`\u{1F50D} [DPI Detection] Strategy 3 (EnumDisplaySettings): physical width = ${t}px`),t>0&&t>this.screenWidth){let n=t/this.screenWidth;return ve.dpi(`\u2705 [DPI Detection] Using EnumDisplaySettings scale: ${n}x (${t}/${this.screenWidth})`),n}}catch(e){ve.dpi(`\u274C [DPI Detection] Strategy 3 failed: ${e.message}`)}return ve.dpi("\u26A0\uFE0F [DPI Detection] All strategies failed, fallback to 1x"),1}async captureFullScreen(){let e=await ww();return{buffer:e.buffer,width:e.width,height:e.height,channels:e.channels}}async getSharedScreenCapture(){let e=Date.now();return this.sharedScreenCache&&e-this.lastCaptureTime<this.CACHE_TTL?this.sharedScreenCache:(this.sharedScreenCache=await this.captureFullScreen(),this.lastCaptureTime=e,this.sharedScreenCache)}clearScreenCache(){}async detectChangedTiles(){return(await this.detectChangedTilesWithHashes()).tiles}async detectChangedTilesWithHashes(){if(this.isProcessing)return{tiles:[],currentHashes:Array.from(this.lastTileChecksums.values())};this.isProcessing=!0;let e=this.metrics.now(),t=e,n=e;try{let i=await this.getSharedScreenCapture();t=this.metrics.now();let s=[],o=[],a=new Map;this.frameCount++;let c=this.activeTileSet;for(let f=0;f<this.totalTiles;f++){if(c&&!c.has(f))continue;let m=this.calculateTileChecksumDirect(i,f);a.set(f,m)}n=this.metrics.now();let u=Array.from(a.values());if(this.lastTileChecksums.size===0){let f=[];for(let y=0;y<this.totalTiles;y++)c&&!c.has(y)||(this.lastTileChecksums.set(y,a.get(y)),f.push(this.processTileAsync(i,y)));let m=await Promise.all(f);return s.push(...m),this._recordFrame(e,t,n,s,i),{tiles:s,currentHashes:u}}for(let f=0;f<this.totalTiles;f++){if(c&&!c.has(f))continue;let m=a.get(f),y=this.lastTileChecksums.get(f);m!==y&&(o.push(f),this.lastTileChecksums.set(f,m))}if(o.length/this.totalTiles>this.changeThreshold){let f=[];for(let y=0;y<this.totalTiles;y++)c&&!c.has(y)||f.push(this.processTileAsync(i,y));let m=await Promise.all(f);s.push(...m.map(y=>({...y,fullRefresh:!0})))}else if(o.length>0){let f=o.map(y=>this.processTileAsync(i,y)),m=await Promise.all(f);s.push(...m)}return this._recordFrame(e,t,n,s,i),{tiles:s,currentHashes:u}}finally{this.isProcessing=!1}}async processTileAsync(e,t,n=null){let i=n||this.extractTile(e,t),s=await this.compressTileImage(i.buffer,i.width,i.height),{row:o,col:a}=this.getTilePosition(t);return{type:"tile-update",tileIndex:t,x:a*this.tileSize,y:o*this.tileSize,width:i.width,height:i.height,imageBuffer:s,hash:this.lastTileChecksums.get(t)??0,timestamp:Date.now(),frameCount:this.frameCount}}calculateTileChecksumDirect(e,t){let{row:n,col:i}=this.getTilePosition(t),s=i*this.tileSize,o=n*this.tileSize,a=Math.min(s+this.tileSize,e.width),c=Math.min(o+this.tileSize,e.height),u=a-s,p=c-o,f=e.channels,m=e.width*f,y=0,_=16;for(let S=0;S<p;S+=4){let A=(S>>2&1)*8,P=(o+S)*m+s*f;for(let L=A;L<u;L+=_){let N=P+L*f;y+=e.buffer[N],y^=e.buffer[N+1],y+=e.buffer[N+2]<<1,y^=e.buffer[N+3]<<2}}return y>>>0}setFocusRect(e){if(!e){this.activeTileSet=null;return}let t=Z.focus.paddingTiles,n=Math.max(0,Math.floor(e.x/this.tileSize)-t),i=Math.max(0,Math.floor(e.y/this.tileSize)-t),s=Math.min(this.tilesPerRow-1,Math.floor((e.x+e.w)/this.tileSize)+t),o=Math.min(this.tilesPerColumn-1,Math.floor((e.y+e.h)/this.tileSize)+t),a=new Set;for(let u=i;u<=o;u++)for(let p=n;p<=s;p++)a.add(u*this.tilesPerRow+p);let c=this.activeTileSet;if(c)for(let u of a)c.has(u)||this.lastTileChecksums.delete(u);this.activeTileSet=a}getTilePosition(e){return{row:Math.floor(e/this.tilesPerRow),col:e%this.tilesPerRow}}extractTile(e,t){let{row:n,col:i}=this.getTilePosition(t),s=i*this.tileSize,o=n*this.tileSize,a=Math.min(s+this.tileSize,e.width),c=Math.min(o+this.tileSize,e.height),u=a-s,p=c-o,f=e.channels,m=u*f,y=Buffer.alloc(u*p*f);for(let _=0;_<p;_++){let S=((o+_)*e.width+s)*f,A=_*m;e.buffer.copy(y,A,S,S+m)}return{buffer:y,width:u,height:p,channels:f,tileIndex:t,x:s,y:o}}async compressTileImage(e,t,n){let i=this.scaleFactor;if(i&&i>0&&i<1){let s=Math.max(1,Math.floor(t*i)),o=Math.max(1,Math.floor(n*i)),{inputFormat:a}=Z.pipeline,c=e,u=4;a==="bgra"&&(c=Buffer.from(e),ah(c));let p=await(0,xS.default)(c,{raw:{width:t,height:n,channels:u}}).resize(s,o,{kernel:"lanczos3",fastShrinkOnLoad:!1}).raw().toBuffer();return ch(p,s,o,4,this.compressionQuality,"rgba")}return ch(e,t,n,4,this.compressionQuality)}pickProfile({zoom:e=1,viewerWidth:t=0,dpr:n=1}={}){let i=Z.pipeline.adaptiveTiers||[];if(!i.length)return null;let s=this.captureWidth||this.screenWidth||1,o=t>0?t:s,a=e>0?e:1,c=n>0?n:1,u=o*a*c/s,p=Z.pipeline.tierHysteresis||0,f=this._currentTier;for(let y of i){let _=f&&y===f?y.minEffective-p:y.minEffective;if(u>=_)return this._currentTier=y,y}let m=i[i.length-1];return this._currentTier=m,m}setProfile(e){if(!e)return;let t=e.outputScale??this.scaleFactor,n=e.jpegQuality??this.compressionQuality;t===this.scaleFactor&&n===this.compressionQuality||(this.scaleFactor=t,this.compressionQuality=n,this.lastTileChecksums.clear())}_recordFrame(e,t,n,i,s){if(this._recordFocusFrame(i),!this.metrics.cfg.metrics)return;let o=this.metrics.now(),a=i.map(u=>u.imageBuffer?.length||0),c=s?s.width*s.height*s.channels:0;this.metrics.record({capture:t-e,checksum:n-t,encode:o-n,total:o-e,changedTiles:i.length,totalTiles:this.totalTiles,tileBytes:a,rawBytes:c})}_recordFocusFrame(e){let t=this.focusStats;t.frames++,t.scanned+=this.activeTileSet?this.activeTileSet.size:this.totalTiles,t.changed+=e.length;for(let c of e)t.bytes+=c.imageBuffer?.length||0;if(t.frames<Z.logging.focusEveryFrames)return;let n=(t.scanned/t.frames).toFixed(0),i=(t.changed/t.frames).toFixed(1),s=(t.bytes/t.frames/1024).toFixed(1),o=this.totalTiles?((1-n/this.totalTiles)*100).toFixed(0):0,a=this.activeTileSet?"focus":"full";ve.focus(`\u{1F3AF} [Focus/${a}] ${t.frames}f | scan ${n}/${this.totalTiles} tiles (saved ${o}%) | changed ${i}/f | data ${s}KB/f`),this.focusStats={frames:0,scanned:0,changed:0,bytes:0}}async getScreenDimensions(){try{let e=await this.captureFullScreen();this.scaledWidth=e.width,this.scaledHeight=e.height,this.tilesPerRow=Math.ceil(e.width/this.tileSize),this.tilesPerColumn=Math.ceil(e.height/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn}catch(e){ve.error("Error getting dimensions:",e)}return{width:this.scaledWidth,height:this.scaledHeight,tileWidth:this.tileSize,tileHeight:this.tileSize,tileCount:this.totalTiles,scaleFactor:this.scaleFactor,originalWidth:this.screenWidth,originalHeight:this.screenHeight}}async compareClientTileHashes(e){if(this.isProcessing)return{tiles:[],currentHashes:[],changedIndices:[]};this.isProcessing=!0;try{let t=await this.getSharedScreenCapture(),n=[],i=[];this.frameCount++;let s=this.activeTileSet,o=new Map;for(let c=0;c<this.totalTiles;c++){if(s&&!s.has(c))continue;let u=this.calculateTileChecksumDirect(t,c);o.set(c,u),this.lastTileChecksums.set(c,u)}if(!e||e.length===0){let c=[];for(let p=0;p<this.totalTiles;p++)s&&!s.has(p)||c.push(this.processTileAsync(t,p));let u=await Promise.all(c);return n.push(...u),{tiles:n,currentHashes:Array.from(o.values())}}for(let c=0;c<this.totalTiles;c++)s&&!s.has(c)||e[c]!==o.get(c)&&i.push(c);if(i.length/this.totalTiles>this.changeThreshold){let c=[];for(let p=0;p<this.totalTiles;p++)s&&!s.has(p)||c.push(this.processTileAsync(t,p));let u=await Promise.all(c);n.push(...u.map(p=>({...p,fullRefresh:!0})))}else if(i.length>0){let c=i.map(p=>this.processTileAsync(t,p)),u=await Promise.all(c);n.push(...u)}return this._recordFocusFrame(n),{tiles:n,currentHashes:Array.from(o.values()),changedIndices:i}}finally{this.isProcessing=!1}}clearMemory(){this.sharedScreenCache=null,this.lastCaptureTime=0,this.lastTileChecksums.clear()}reset(){this.lastTileChecksums.clear(),this.frameCount=0}cleanup(){try{Ts.default.existsSync(this.tempDir)&&Ts.default.readdirSync(this.tempDir).forEach(t=>Ts.default.unlinkSync(Bl.default.join(this.tempDir,t)))}catch(e){ve.warn(`Cleanup error: ${e.message}`)}}}});var wS={};Xr(wS,{ResourceManager:()=>Ah});var Ah,SS=Ce(()=>{bt();Ah=class{constructor(){this.activeClients=new Map,this.activeTimers=new Map,this.chunkTimers=new Map,this.memoryCheckInterval=null}startResourceMonitoring(){this.memoryCheckInterval=setInterval(()=>{let e=process.memoryUsage(),t=Math.round(e.heapUsed/1024/1024);t>Z.resourceManagement.memoryWarningThreshold&&(console.warn(`\u26A0\uFE0F High memory: ${t}MB`),this.cleanupInactiveClients())},Z.resourceManagement.memoryCheckInterval)}stopResourceMonitoring(){this.memoryCheckInterval&&(clearInterval(this.memoryCheckInterval),this.memoryCheckInterval=null)}addClient(e,t){this.activeClients.set(e,{...t,lastActivity:Date.now()})}getClient(e){return this.activeClients.get(e)}updateClientActivity(e){let t=this.activeClients.get(e);t&&(t.lastActivity=Date.now())}cleanupInactiveClients(){let e=Date.now(),t=Z.resourceManagement.inactiveTimeout;for(let[n,i]of this.activeClients.entries())e-i.lastActivity>t&&(console.log(`\u{1F9F9} Cleaning inactive client: ${n}`),this.cleanupClientResources(n,i),this.activeClients.delete(n))}cleanupClientResources(e,t){try{t.isStreaming=!1,t?.streamingTimeout&&(clearTimeout(t.streamingTimeout),t.streamingTimeout=null),t?.screenInterval&&(clearInterval(t.screenInterval),t.screenInterval=null);let n=this.activeTimers.get(e);n&&(n.forEach(s=>clearTimeout(s)),this.activeTimers.delete(e));let i=this.chunkTimers.get(e);i&&(i.forEach(s=>clearTimeout(s)),this.chunkTimers.delete(e)),t?.tileManager&&(t.tileManager.clearMemory(),t.tileManager.cleanup(),t.tileManager.reset())}catch(n){console.error(`Error cleaning up ${e}:`,n.message)}}getStreamingConfig(){return Z.streaming}getWebRTCConfig(){return Z.webrtc}removeClient(e){let t=this.activeClients.get(e);t&&(this.cleanupClientResources(e,t),this.activeClients.delete(e))}getChunkTimers(e){return this.chunkTimers.has(e)||this.chunkTimers.set(e,new Set),this.chunkTimers.get(e)}cleanupAll(){this.stopResourceMonitoring();for(let[e,t]of this.activeClients.entries())this.cleanupClientResources(e,t);this.activeClients.clear(),this.activeTimers.clear(),this.chunkTimers.clear()}}});var ES={};Xr(ES,{ScreenUpdateHelper:()=>Rh});var Rh,TS=Ce(()=>{bt();Rh=class{constructor(e){this.resourceManager=e}async sendTilesInChunks(e,t,n,i=!1){if(!t||t.length===0)return;let s=Z.streaming.chunkSize,o=[];for(let c=0;c<t.length;c+=s)o.push(t.slice(c,c+s));let a=this.resourceManager.getChunkTimers(e.id);for(let c=0;c<o.length;c++){let u=o[c],p=c===o.length-1,f=setTimeout(()=>{a.delete(f),e.connected&&e.emit("tiles-data",{tiles:u,timestamp:n,forceRefresh:!1,userAction:i,chunkInfo:{chunkIndex:c,totalChunks:o.length,isLastChunk:p}})},c*Z.streaming.chunkDelay);a.add(f)}}}});var CS={};Xr(CS,{MouseHandler:()=>kh});var kh,AS=Ce(()=>{bt();kh=class{constructor(e,t){this.robot=e,this.resourceManager=t,this.lastMouseMove=0}setupMouseHandlers(e,t){let n=this.robot;e.on("mouse-move",t(i=>{let s=Date.now();if(!(s-this.lastMouseMove<Z.throttling.mouseThrottle)){this.lastMouseMove=s;try{let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),u=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(u,p),this.resourceManager.updateClientActivity(e.id)}catch(o){console.error("Mouse move error:",o.message)}}})),e.on("mouse-click",t(async i=>{try{let s=this.resourceManager.getClient(e.id);if(!s)return;let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),u=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(u,p),n.mouseClick(i.button||"left",i.double||!1),s.idleFrameCount=0,this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Mouse click error:",s.message)}})),e.on("mouse-press",t(async i=>{try{if(!this.resourceManager.getClient(e.id))return;let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),u=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(u,p),n.mouseToggle("down",i.button||"left"),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Mouse press error:",s.message)}})),e.on("mouse-release",t(async i=>{try{if(!this.resourceManager.getClient(e.id))return;let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),u=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(u,p),n.mouseToggle("up",i.button||"left"),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Mouse release error:",s.message)}})),e.on("scroll",t(async i=>{try{let{direction:s,amount:o=60,horizontal:a=!1}=i,c=this.resourceManager.getClient(e.id);if(!c)return;let u=0,p=0;a||s==="left"||s==="right"?u=s==="right"?o:-o:p=s==="down"?-o:o,n.scrollMouse(u,p),c.idleFrameCount=0,this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Scroll error:",s.message)}})),e.on("mouse-drag-select",t(i=>{try{let{startX:s,startY:o,endX:a,endY:c}=i,u=n.getScreenSize(),p=Math.round(s/100*u.width),f=Math.round(o/100*u.height),m=Math.round(a/100*u.width),y=Math.round(c/100*u.height),_=Math.max(0,Math.min(u.width-1,p)),S=Math.max(0,Math.min(u.height-1,f)),A=Math.max(0,Math.min(u.width-1,m)),P=Math.max(0,Math.min(u.height-1,y));n.moveMouse(_,S),n.mouseToggle("down","left"),n.dragMouse(A,P),n.mouseToggle("up","left"),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Drag selection error:",s.message)}}))}}});var kS={};Xr(kS,{KeyboardHandler:()=>Oh});function QB(r){let e;r.type==="missionControl"?e='tell application "System Events" to key code 160':e=`tell application "System Events" to key code ${r.keyCode} using ${r.mods}`,(0,RS.execFile)("osascript",["-e",e],t=>{t&&console.error("osascript error:",t.message)})}var RS,Oh,OS=Ce(()=>{RS=require("child_process");bt();Oh=class{constructor(e,t){this.robot=e,this.resourceManager=t,this.lastKeyPress=0,this.lastTypeText=0}setupKeyboardHandlers(e,t){let n=this.robot;e.on("key-press",t(i=>{let s=Date.now();if(!(s-this.lastKeyPress<Z.throttling.keyThrottle)){this.lastKeyPress=s;try{if(!i.key||typeof i.key!="string")return;let o=this.resourceManager.getClient(e.id),a=i.key,c=i.modifier||[];if(a.length===1){n.keyTap(a,c);for(let u of c)n.keyToggle(u,"up")}else{let p={return:"enter"}[a.toLowerCase()]??a.toLowerCase();n.keyTap(p,c)}o&&(o.idleFrameCount=0),this.resourceManager.updateClientActivity(e.id)}catch(o){console.error("Key press error:",o.message)}}})),e.on("desktop-switch",t(i=>{try{let s=i?.direction,o=Z.desktopSwitch[process.platform]?.[s];if(!o)return;process.platform==="darwin"?QB(o):n.keyTap(o[0],o[1]);let a=this.resourceManager.getClient(e.id);a&&(a.idleFrameCount=0),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Desktop switch error:",s.message)}})),e.on("type-text",t(i=>{let s=Date.now();if(!(s-this.lastTypeText<Z.throttling.typeTextThrottle)){this.lastTypeText=s;try{if(!i.text||typeof i.text!="string")return;let o=i.text;o.length>Z.throttling.maxTextLength&&(o=o.substring(0,Z.throttling.maxTextLength));let a=o.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),c=this.resourceManager.getClient(e.id);setTimeout(()=>{try{n.typeString(a),this.resourceManager.updateClientActivity(e.id),c&&(c.idleFrameCount=0,c.tileManager&&c.tileManager.clearScreenCache())}catch(u){console.error("Robot typeString error:",u.message)}},10)}catch(o){console.error("Type text error:",o.message)}}}))}}});var Fh=O((cE,jh)=>{(function(r,e){"use strict";function t(T,l){if(!T)throw new Error(l||"Assertion failed")}function n(T,l){T.super_=l;var h=function(){};h.prototype=l.prototype,T.prototype=new h,T.prototype.constructor=T}function i(T,l,h){if(i.isBN(T))return T;this.negative=0,this.words=null,this.length=0,this.red=null,T!==null&&((l==="le"||l==="be")&&(h=l,l=10),this._init(T||0,l||10,h||"be"))}typeof r=="object"?r.exports=i:e.BN=i,i.BN=i,i.wordSize=26;var s;try{typeof window<"u"&&typeof window.Buffer<"u"?s=window.Buffer:s=require("buffer").Buffer}catch{}i.isBN=function(l){return l instanceof i?!0:l!==null&&typeof l=="object"&&l.constructor.wordSize===i.wordSize&&Array.isArray(l.words)},i.max=function(l,h){return l.cmp(h)>0?l:h},i.min=function(l,h){return l.cmp(h)<0?l:h},i.prototype._init=function(l,h,x){if(typeof l=="number")return this._initNumber(l,h,x);if(typeof l=="object")return this._initArray(l,h,x);h==="hex"&&(h=16),t(h===(h|0)&&h>=2&&h<=36),l=l.toString().replace(/\s+/g,"");var w=0;l[0]==="-"&&(w++,this.negative=1),w<l.length&&(h===16?this._parseHex(l,w,x):(this._parseBase(l,h,w),x==="le"&&this._initArray(this.toArray(),h,x)))},i.prototype._initNumber=function(l,h,x){l<0&&(this.negative=1,l=-l),l<67108864?(this.words=[l&67108863],this.length=1):l<4503599627370496?(this.words=[l&67108863,l/67108864&67108863],this.length=2):(t(l<9007199254740992),this.words=[l&67108863,l/67108864&67108863,1],this.length=3),x==="le"&&this._initArray(this.toArray(),h,x)},i.prototype._initArray=function(l,h,x){if(t(typeof l.length=="number"),l.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(l.length/3),this.words=new Array(this.length);for(var w=0;w<this.length;w++)this.words[w]=0;var g,v,C=0;if(x==="be")for(w=l.length-1,g=0;w>=0;w-=3)v=l[w]|l[w-1]<<8|l[w-2]<<16,this.words[g]|=v<<C&67108863,this.words[g+1]=v>>>26-C&67108863,C+=24,C>=26&&(C-=26,g++);else if(x==="le")for(w=0,g=0;w<l.length;w+=3)v=l[w]|l[w+1]<<8|l[w+2]<<16,this.words[g]|=v<<C&67108863,this.words[g+1]=v>>>26-C&67108863,C+=24,C>=26&&(C-=26,g++);return this.strip()};function o(T,l){var h=T.charCodeAt(l);return h>=65&&h<=70?h-55:h>=97&&h<=102?h-87:h-48&15}function a(T,l,h){var x=o(T,h);return h-1>=l&&(x|=o(T,h-1)<<4),x}i.prototype._parseHex=function(l,h,x){this.length=Math.ceil((l.length-h)/6),this.words=new Array(this.length);for(var w=0;w<this.length;w++)this.words[w]=0;var g=0,v=0,C;if(x==="be")for(w=l.length-1;w>=h;w-=2)C=a(l,h,w)<<g,this.words[v]|=C&67108863,g>=18?(g-=18,v+=1,this.words[v]|=C>>>26):g+=8;else{var b=l.length-h;for(w=b%2===0?h+1:h;w<l.length;w+=2)C=a(l,h,w)<<g,this.words[v]|=C&67108863,g>=18?(g-=18,v+=1,this.words[v]|=C>>>26):g+=8}this.strip()};function c(T,l,h,x){for(var w=0,g=Math.min(T.length,h),v=l;v<g;v++){var C=T.charCodeAt(v)-48;w*=x,C>=49?w+=C-49+10:C>=17?w+=C-17+10:w+=C}return w}i.prototype._parseBase=function(l,h,x){this.words=[0],this.length=1;for(var w=0,g=1;g<=67108863;g*=h)w++;w--,g=g/h|0;for(var v=l.length-x,C=v%w,b=Math.min(v,v-C)+x,d=0,E=x;E<b;E+=w)d=c(l,E,E+w,h),this.imuln(g),this.words[0]+d<67108864?this.words[0]+=d:this._iaddn(d);if(C!==0){var U=1;for(d=c(l,E,l.length,h),E=0;E<C;E++)U*=h;this.imuln(U),this.words[0]+d<67108864?this.words[0]+=d:this._iaddn(d)}this.strip()},i.prototype.copy=function(l){l.words=new Array(this.length);for(var h=0;h<this.length;h++)l.words[h]=this.words[h];l.length=this.length,l.negative=this.negative,l.red=this.red},i.prototype.clone=function(){var l=new i(null);return this.copy(l),l},i.prototype._expand=function(l){for(;this.length<l;)this.words[this.length++]=0;return this},i.prototype.strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},i.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var u=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],p=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];i.prototype.toString=function(l,h){l=l||10,h=h|0||1;var x;if(l===16||l==="hex"){x="";for(var w=0,g=0,v=0;v<this.length;v++){var C=this.words[v],b=((C<<w|g)&16777215).toString(16);g=C>>>24-w&16777215,w+=2,w>=26&&(w-=26,v--),g!==0||v!==this.length-1?x=u[6-b.length]+b+x:x=b+x}for(g!==0&&(x=g.toString(16)+x);x.length%h!==0;)x="0"+x;return this.negative!==0&&(x="-"+x),x}if(l===(l|0)&&l>=2&&l<=36){var d=p[l],E=f[l];x="";var U=this.clone();for(U.negative=0;!U.isZero();){var I=U.modn(E).toString(l);U=U.idivn(E),U.isZero()?x=I+x:x=u[d-I.length]+I+x}for(this.isZero()&&(x="0"+x);x.length%h!==0;)x="0"+x;return this.negative!==0&&(x="-"+x),x}t(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var l=this.words[0];return this.length===2?l+=this.words[1]*67108864:this.length===3&&this.words[2]===1?l+=4503599627370496+this.words[1]*67108864:this.length>2&&t(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-l:l},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(l,h){return t(typeof s<"u"),this.toArrayLike(s,l,h)},i.prototype.toArray=function(l,h){return this.toArrayLike(Array,l,h)},i.prototype.toArrayLike=function(l,h,x){var w=this.byteLength(),g=x||Math.max(1,w);t(w<=g,"byte array longer than desired length"),t(g>0,"Requested array length <= 0"),this.strip();var v=h==="le",C=new l(g),b,d,E=this.clone();if(v){for(d=0;!E.isZero();d++)b=E.andln(255),E.iushrn(8),C[d]=b;for(;d<g;d++)C[d]=0}else{for(d=0;d<g-w;d++)C[d]=0;for(d=0;!E.isZero();d++)b=E.andln(255),E.iushrn(8),C[g-d-1]=b}return C},Math.clz32?i.prototype._countBits=function(l){return 32-Math.clz32(l)}:i.prototype._countBits=function(l){var h=l,x=0;return h>=4096&&(x+=13,h>>>=13),h>=64&&(x+=7,h>>>=7),h>=8&&(x+=4,h>>>=4),h>=2&&(x+=2,h>>>=2),x+h},i.prototype._zeroBits=function(l){if(l===0)return 26;var h=l,x=0;return(h&8191)===0&&(x+=13,h>>>=13),(h&127)===0&&(x+=7,h>>>=7),(h&15)===0&&(x+=4,h>>>=4),(h&3)===0&&(x+=2,h>>>=2),(h&1)===0&&x++,x},i.prototype.bitLength=function(){var l=this.words[this.length-1],h=this._countBits(l);return(this.length-1)*26+h};function m(T){for(var l=new Array(T.bitLength()),h=0;h<l.length;h++){var x=h/26|0,w=h%26;l[h]=(T.words[x]&1<<w)>>>w}return l}i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var l=0,h=0;h<this.length;h++){var x=this._zeroBits(this.words[h]);if(l+=x,x!==26)break}return l},i.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},i.prototype.toTwos=function(l){return this.negative!==0?this.abs().inotn(l).iaddn(1):this.clone()},i.prototype.fromTwos=function(l){return this.testn(l-1)?this.notn(l).iaddn(1).ineg():this.clone()},i.prototype.isNeg=function(){return this.negative!==0},i.prototype.neg=function(){return this.clone().ineg()},i.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},i.prototype.iuor=function(l){for(;this.length<l.length;)this.words[this.length++]=0;for(var h=0;h<l.length;h++)this.words[h]=this.words[h]|l.words[h];return this.strip()},i.prototype.ior=function(l){return t((this.negative|l.negative)===0),this.iuor(l)},i.prototype.or=function(l){return this.length>l.length?this.clone().ior(l):l.clone().ior(this)},i.prototype.uor=function(l){return this.length>l.length?this.clone().iuor(l):l.clone().iuor(this)},i.prototype.iuand=function(l){var h;this.length>l.length?h=l:h=this;for(var x=0;x<h.length;x++)this.words[x]=this.words[x]&l.words[x];return this.length=h.length,this.strip()},i.prototype.iand=function(l){return t((this.negative|l.negative)===0),this.iuand(l)},i.prototype.and=function(l){return this.length>l.length?this.clone().iand(l):l.clone().iand(this)},i.prototype.uand=function(l){return this.length>l.length?this.clone().iuand(l):l.clone().iuand(this)},i.prototype.iuxor=function(l){var h,x;this.length>l.length?(h=this,x=l):(h=l,x=this);for(var w=0;w<x.length;w++)this.words[w]=h.words[w]^x.words[w];if(this!==h)for(;w<h.length;w++)this.words[w]=h.words[w];return this.length=h.length,this.strip()},i.prototype.ixor=function(l){return t((this.negative|l.negative)===0),this.iuxor(l)},i.prototype.xor=function(l){return this.length>l.length?this.clone().ixor(l):l.clone().ixor(this)},i.prototype.uxor=function(l){return this.length>l.length?this.clone().iuxor(l):l.clone().iuxor(this)},i.prototype.inotn=function(l){t(typeof l=="number"&&l>=0);var h=Math.ceil(l/26)|0,x=l%26;this._expand(h),x>0&&h--;for(var w=0;w<h;w++)this.words[w]=~this.words[w]&67108863;return x>0&&(this.words[w]=~this.words[w]&67108863>>26-x),this.strip()},i.prototype.notn=function(l){return this.clone().inotn(l)},i.prototype.setn=function(l,h){t(typeof l=="number"&&l>=0);var x=l/26|0,w=l%26;return this._expand(x+1),h?this.words[x]=this.words[x]|1<<w:this.words[x]=this.words[x]&~(1<<w),this.strip()},i.prototype.iadd=function(l){var h;if(this.negative!==0&&l.negative===0)return this.negative=0,h=this.isub(l),this.negative^=1,this._normSign();if(this.negative===0&&l.negative!==0)return l.negative=0,h=this.isub(l),l.negative=1,h._normSign();var x,w;this.length>l.length?(x=this,w=l):(x=l,w=this);for(var g=0,v=0;v<w.length;v++)h=(x.words[v]|0)+(w.words[v]|0)+g,this.words[v]=h&67108863,g=h>>>26;for(;g!==0&&v<x.length;v++)h=(x.words[v]|0)+g,this.words[v]=h&67108863,g=h>>>26;if(this.length=x.length,g!==0)this.words[this.length]=g,this.length++;else if(x!==this)for(;v<x.length;v++)this.words[v]=x.words[v];return this},i.prototype.add=function(l){var h;return l.negative!==0&&this.negative===0?(l.negative=0,h=this.sub(l),l.negative^=1,h):l.negative===0&&this.negative!==0?(this.negative=0,h=l.sub(this),this.negative=1,h):this.length>l.length?this.clone().iadd(l):l.clone().iadd(this)},i.prototype.isub=function(l){if(l.negative!==0){l.negative=0;var h=this.iadd(l);return l.negative=1,h._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(l),this.negative=1,this._normSign();var x=this.cmp(l);if(x===0)return this.negative=0,this.length=1,this.words[0]=0,this;var w,g;x>0?(w=this,g=l):(w=l,g=this);for(var v=0,C=0;C<g.length;C++)h=(w.words[C]|0)-(g.words[C]|0)+v,v=h>>26,this.words[C]=h&67108863;for(;v!==0&&C<w.length;C++)h=(w.words[C]|0)+v,v=h>>26,this.words[C]=h&67108863;if(v===0&&C<w.length&&w!==this)for(;C<w.length;C++)this.words[C]=w.words[C];return this.length=Math.max(this.length,C),w!==this&&(this.negative=1),this.strip()},i.prototype.sub=function(l){return this.clone().isub(l)};function y(T,l,h){h.negative=l.negative^T.negative;var x=T.length+l.length|0;h.length=x,x=x-1|0;var w=T.words[0]|0,g=l.words[0]|0,v=w*g,C=v&67108863,b=v/67108864|0;h.words[0]=C;for(var d=1;d<x;d++){for(var E=b>>>26,U=b&67108863,I=Math.min(d,l.length-1),D=Math.max(0,d-T.length+1);D<=I;D++){var H=d-D|0;w=T.words[H]|0,g=l.words[D]|0,v=w*g+U,E+=v/67108864|0,U=v&67108863}h.words[d]=U|0,b=E|0}return b!==0?h.words[d]=b|0:h.length--,h.strip()}var _=function(l,h,x){var w=l.words,g=h.words,v=x.words,C=0,b,d,E,U=w[0]|0,I=U&8191,D=U>>>13,H=w[1]|0,V=H&8191,B=H>>>13,me=w[2]|0,ie=me&8191,R=me>>>13,Y=w[3]|0,k=Y&8191,j=Y>>>13,J=w[4]|0,K=J&8191,z=J>>>13,ge=w[5]|0,re=ge&8191,Me=ge>>>13,rv=w[6]|0,Ie=rv&8191,Ne=rv>>>13,nv=w[7]|0,Le=nv&8191,De=nv>>>13,iv=w[8]|0,Be=iv&8191,je=iv>>>13,sv=w[9]|0,Fe=sv&8191,$e=sv>>>13,ov=g[0]|0,He=ov&8191,Ue=ov>>>13,av=g[1]|0,qe=av&8191,We=av>>>13,cv=g[2]|0,Ge=cv&8191,ze=cv>>>13,lv=g[3]|0,Ve=lv&8191,Ke=lv>>>13,uv=g[4]|0,Ye=uv&8191,Xe=uv>>>13,pv=g[5]|0,Je=pv&8191,Qe=pv>>>13,fv=g[6]|0,Ze=fv&8191,et=fv>>>13,dv=g[7]|0,tt=dv&8191,rt=dv>>>13,hv=g[8]|0,nt=hv&8191,it=hv>>>13,mv=g[9]|0,st=mv&8191,ot=mv>>>13;x.negative=l.negative^h.negative,x.length=19,b=Math.imul(I,He),d=Math.imul(I,Ue),d=d+Math.imul(D,He)|0,E=Math.imul(D,Ue);var rp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(rp>>>26)|0,rp&=67108863,b=Math.imul(V,He),d=Math.imul(V,Ue),d=d+Math.imul(B,He)|0,E=Math.imul(B,Ue),b=b+Math.imul(I,qe)|0,d=d+Math.imul(I,We)|0,d=d+Math.imul(D,qe)|0,E=E+Math.imul(D,We)|0;var np=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(np>>>26)|0,np&=67108863,b=Math.imul(ie,He),d=Math.imul(ie,Ue),d=d+Math.imul(R,He)|0,E=Math.imul(R,Ue),b=b+Math.imul(V,qe)|0,d=d+Math.imul(V,We)|0,d=d+Math.imul(B,qe)|0,E=E+Math.imul(B,We)|0,b=b+Math.imul(I,Ge)|0,d=d+Math.imul(I,ze)|0,d=d+Math.imul(D,Ge)|0,E=E+Math.imul(D,ze)|0;var ip=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(ip>>>26)|0,ip&=67108863,b=Math.imul(k,He),d=Math.imul(k,Ue),d=d+Math.imul(j,He)|0,E=Math.imul(j,Ue),b=b+Math.imul(ie,qe)|0,d=d+Math.imul(ie,We)|0,d=d+Math.imul(R,qe)|0,E=E+Math.imul(R,We)|0,b=b+Math.imul(V,Ge)|0,d=d+Math.imul(V,ze)|0,d=d+Math.imul(B,Ge)|0,E=E+Math.imul(B,ze)|0,b=b+Math.imul(I,Ve)|0,d=d+Math.imul(I,Ke)|0,d=d+Math.imul(D,Ve)|0,E=E+Math.imul(D,Ke)|0;var sp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(sp>>>26)|0,sp&=67108863,b=Math.imul(K,He),d=Math.imul(K,Ue),d=d+Math.imul(z,He)|0,E=Math.imul(z,Ue),b=b+Math.imul(k,qe)|0,d=d+Math.imul(k,We)|0,d=d+Math.imul(j,qe)|0,E=E+Math.imul(j,We)|0,b=b+Math.imul(ie,Ge)|0,d=d+Math.imul(ie,ze)|0,d=d+Math.imul(R,Ge)|0,E=E+Math.imul(R,ze)|0,b=b+Math.imul(V,Ve)|0,d=d+Math.imul(V,Ke)|0,d=d+Math.imul(B,Ve)|0,E=E+Math.imul(B,Ke)|0,b=b+Math.imul(I,Ye)|0,d=d+Math.imul(I,Xe)|0,d=d+Math.imul(D,Ye)|0,E=E+Math.imul(D,Xe)|0;var op=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(op>>>26)|0,op&=67108863,b=Math.imul(re,He),d=Math.imul(re,Ue),d=d+Math.imul(Me,He)|0,E=Math.imul(Me,Ue),b=b+Math.imul(K,qe)|0,d=d+Math.imul(K,We)|0,d=d+Math.imul(z,qe)|0,E=E+Math.imul(z,We)|0,b=b+Math.imul(k,Ge)|0,d=d+Math.imul(k,ze)|0,d=d+Math.imul(j,Ge)|0,E=E+Math.imul(j,ze)|0,b=b+Math.imul(ie,Ve)|0,d=d+Math.imul(ie,Ke)|0,d=d+Math.imul(R,Ve)|0,E=E+Math.imul(R,Ke)|0,b=b+Math.imul(V,Ye)|0,d=d+Math.imul(V,Xe)|0,d=d+Math.imul(B,Ye)|0,E=E+Math.imul(B,Xe)|0,b=b+Math.imul(I,Je)|0,d=d+Math.imul(I,Qe)|0,d=d+Math.imul(D,Je)|0,E=E+Math.imul(D,Qe)|0;var ap=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(ap>>>26)|0,ap&=67108863,b=Math.imul(Ie,He),d=Math.imul(Ie,Ue),d=d+Math.imul(Ne,He)|0,E=Math.imul(Ne,Ue),b=b+Math.imul(re,qe)|0,d=d+Math.imul(re,We)|0,d=d+Math.imul(Me,qe)|0,E=E+Math.imul(Me,We)|0,b=b+Math.imul(K,Ge)|0,d=d+Math.imul(K,ze)|0,d=d+Math.imul(z,Ge)|0,E=E+Math.imul(z,ze)|0,b=b+Math.imul(k,Ve)|0,d=d+Math.imul(k,Ke)|0,d=d+Math.imul(j,Ve)|0,E=E+Math.imul(j,Ke)|0,b=b+Math.imul(ie,Ye)|0,d=d+Math.imul(ie,Xe)|0,d=d+Math.imul(R,Ye)|0,E=E+Math.imul(R,Xe)|0,b=b+Math.imul(V,Je)|0,d=d+Math.imul(V,Qe)|0,d=d+Math.imul(B,Je)|0,E=E+Math.imul(B,Qe)|0,b=b+Math.imul(I,Ze)|0,d=d+Math.imul(I,et)|0,d=d+Math.imul(D,Ze)|0,E=E+Math.imul(D,et)|0;var cp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(cp>>>26)|0,cp&=67108863,b=Math.imul(Le,He),d=Math.imul(Le,Ue),d=d+Math.imul(De,He)|0,E=Math.imul(De,Ue),b=b+Math.imul(Ie,qe)|0,d=d+Math.imul(Ie,We)|0,d=d+Math.imul(Ne,qe)|0,E=E+Math.imul(Ne,We)|0,b=b+Math.imul(re,Ge)|0,d=d+Math.imul(re,ze)|0,d=d+Math.imul(Me,Ge)|0,E=E+Math.imul(Me,ze)|0,b=b+Math.imul(K,Ve)|0,d=d+Math.imul(K,Ke)|0,d=d+Math.imul(z,Ve)|0,E=E+Math.imul(z,Ke)|0,b=b+Math.imul(k,Ye)|0,d=d+Math.imul(k,Xe)|0,d=d+Math.imul(j,Ye)|0,E=E+Math.imul(j,Xe)|0,b=b+Math.imul(ie,Je)|0,d=d+Math.imul(ie,Qe)|0,d=d+Math.imul(R,Je)|0,E=E+Math.imul(R,Qe)|0,b=b+Math.imul(V,Ze)|0,d=d+Math.imul(V,et)|0,d=d+Math.imul(B,Ze)|0,E=E+Math.imul(B,et)|0,b=b+Math.imul(I,tt)|0,d=d+Math.imul(I,rt)|0,d=d+Math.imul(D,tt)|0,E=E+Math.imul(D,rt)|0;var lp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(lp>>>26)|0,lp&=67108863,b=Math.imul(Be,He),d=Math.imul(Be,Ue),d=d+Math.imul(je,He)|0,E=Math.imul(je,Ue),b=b+Math.imul(Le,qe)|0,d=d+Math.imul(Le,We)|0,d=d+Math.imul(De,qe)|0,E=E+Math.imul(De,We)|0,b=b+Math.imul(Ie,Ge)|0,d=d+Math.imul(Ie,ze)|0,d=d+Math.imul(Ne,Ge)|0,E=E+Math.imul(Ne,ze)|0,b=b+Math.imul(re,Ve)|0,d=d+Math.imul(re,Ke)|0,d=d+Math.imul(Me,Ve)|0,E=E+Math.imul(Me,Ke)|0,b=b+Math.imul(K,Ye)|0,d=d+Math.imul(K,Xe)|0,d=d+Math.imul(z,Ye)|0,E=E+Math.imul(z,Xe)|0,b=b+Math.imul(k,Je)|0,d=d+Math.imul(k,Qe)|0,d=d+Math.imul(j,Je)|0,E=E+Math.imul(j,Qe)|0,b=b+Math.imul(ie,Ze)|0,d=d+Math.imul(ie,et)|0,d=d+Math.imul(R,Ze)|0,E=E+Math.imul(R,et)|0,b=b+Math.imul(V,tt)|0,d=d+Math.imul(V,rt)|0,d=d+Math.imul(B,tt)|0,E=E+Math.imul(B,rt)|0,b=b+Math.imul(I,nt)|0,d=d+Math.imul(I,it)|0,d=d+Math.imul(D,nt)|0,E=E+Math.imul(D,it)|0;var up=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(up>>>26)|0,up&=67108863,b=Math.imul(Fe,He),d=Math.imul(Fe,Ue),d=d+Math.imul($e,He)|0,E=Math.imul($e,Ue),b=b+Math.imul(Be,qe)|0,d=d+Math.imul(Be,We)|0,d=d+Math.imul(je,qe)|0,E=E+Math.imul(je,We)|0,b=b+Math.imul(Le,Ge)|0,d=d+Math.imul(Le,ze)|0,d=d+Math.imul(De,Ge)|0,E=E+Math.imul(De,ze)|0,b=b+Math.imul(Ie,Ve)|0,d=d+Math.imul(Ie,Ke)|0,d=d+Math.imul(Ne,Ve)|0,E=E+Math.imul(Ne,Ke)|0,b=b+Math.imul(re,Ye)|0,d=d+Math.imul(re,Xe)|0,d=d+Math.imul(Me,Ye)|0,E=E+Math.imul(Me,Xe)|0,b=b+Math.imul(K,Je)|0,d=d+Math.imul(K,Qe)|0,d=d+Math.imul(z,Je)|0,E=E+Math.imul(z,Qe)|0,b=b+Math.imul(k,Ze)|0,d=d+Math.imul(k,et)|0,d=d+Math.imul(j,Ze)|0,E=E+Math.imul(j,et)|0,b=b+Math.imul(ie,tt)|0,d=d+Math.imul(ie,rt)|0,d=d+Math.imul(R,tt)|0,E=E+Math.imul(R,rt)|0,b=b+Math.imul(V,nt)|0,d=d+Math.imul(V,it)|0,d=d+Math.imul(B,nt)|0,E=E+Math.imul(B,it)|0,b=b+Math.imul(I,st)|0,d=d+Math.imul(I,ot)|0,d=d+Math.imul(D,st)|0,E=E+Math.imul(D,ot)|0;var pp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(pp>>>26)|0,pp&=67108863,b=Math.imul(Fe,qe),d=Math.imul(Fe,We),d=d+Math.imul($e,qe)|0,E=Math.imul($e,We),b=b+Math.imul(Be,Ge)|0,d=d+Math.imul(Be,ze)|0,d=d+Math.imul(je,Ge)|0,E=E+Math.imul(je,ze)|0,b=b+Math.imul(Le,Ve)|0,d=d+Math.imul(Le,Ke)|0,d=d+Math.imul(De,Ve)|0,E=E+Math.imul(De,Ke)|0,b=b+Math.imul(Ie,Ye)|0,d=d+Math.imul(Ie,Xe)|0,d=d+Math.imul(Ne,Ye)|0,E=E+Math.imul(Ne,Xe)|0,b=b+Math.imul(re,Je)|0,d=d+Math.imul(re,Qe)|0,d=d+Math.imul(Me,Je)|0,E=E+Math.imul(Me,Qe)|0,b=b+Math.imul(K,Ze)|0,d=d+Math.imul(K,et)|0,d=d+Math.imul(z,Ze)|0,E=E+Math.imul(z,et)|0,b=b+Math.imul(k,tt)|0,d=d+Math.imul(k,rt)|0,d=d+Math.imul(j,tt)|0,E=E+Math.imul(j,rt)|0,b=b+Math.imul(ie,nt)|0,d=d+Math.imul(ie,it)|0,d=d+Math.imul(R,nt)|0,E=E+Math.imul(R,it)|0,b=b+Math.imul(V,st)|0,d=d+Math.imul(V,ot)|0,d=d+Math.imul(B,st)|0,E=E+Math.imul(B,ot)|0;var fp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(fp>>>26)|0,fp&=67108863,b=Math.imul(Fe,Ge),d=Math.imul(Fe,ze),d=d+Math.imul($e,Ge)|0,E=Math.imul($e,ze),b=b+Math.imul(Be,Ve)|0,d=d+Math.imul(Be,Ke)|0,d=d+Math.imul(je,Ve)|0,E=E+Math.imul(je,Ke)|0,b=b+Math.imul(Le,Ye)|0,d=d+Math.imul(Le,Xe)|0,d=d+Math.imul(De,Ye)|0,E=E+Math.imul(De,Xe)|0,b=b+Math.imul(Ie,Je)|0,d=d+Math.imul(Ie,Qe)|0,d=d+Math.imul(Ne,Je)|0,E=E+Math.imul(Ne,Qe)|0,b=b+Math.imul(re,Ze)|0,d=d+Math.imul(re,et)|0,d=d+Math.imul(Me,Ze)|0,E=E+Math.imul(Me,et)|0,b=b+Math.imul(K,tt)|0,d=d+Math.imul(K,rt)|0,d=d+Math.imul(z,tt)|0,E=E+Math.imul(z,rt)|0,b=b+Math.imul(k,nt)|0,d=d+Math.imul(k,it)|0,d=d+Math.imul(j,nt)|0,E=E+Math.imul(j,it)|0,b=b+Math.imul(ie,st)|0,d=d+Math.imul(ie,ot)|0,d=d+Math.imul(R,st)|0,E=E+Math.imul(R,ot)|0;var dp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(dp>>>26)|0,dp&=67108863,b=Math.imul(Fe,Ve),d=Math.imul(Fe,Ke),d=d+Math.imul($e,Ve)|0,E=Math.imul($e,Ke),b=b+Math.imul(Be,Ye)|0,d=d+Math.imul(Be,Xe)|0,d=d+Math.imul(je,Ye)|0,E=E+Math.imul(je,Xe)|0,b=b+Math.imul(Le,Je)|0,d=d+Math.imul(Le,Qe)|0,d=d+Math.imul(De,Je)|0,E=E+Math.imul(De,Qe)|0,b=b+Math.imul(Ie,Ze)|0,d=d+Math.imul(Ie,et)|0,d=d+Math.imul(Ne,Ze)|0,E=E+Math.imul(Ne,et)|0,b=b+Math.imul(re,tt)|0,d=d+Math.imul(re,rt)|0,d=d+Math.imul(Me,tt)|0,E=E+Math.imul(Me,rt)|0,b=b+Math.imul(K,nt)|0,d=d+Math.imul(K,it)|0,d=d+Math.imul(z,nt)|0,E=E+Math.imul(z,it)|0,b=b+Math.imul(k,st)|0,d=d+Math.imul(k,ot)|0,d=d+Math.imul(j,st)|0,E=E+Math.imul(j,ot)|0;var hp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(hp>>>26)|0,hp&=67108863,b=Math.imul(Fe,Ye),d=Math.imul(Fe,Xe),d=d+Math.imul($e,Ye)|0,E=Math.imul($e,Xe),b=b+Math.imul(Be,Je)|0,d=d+Math.imul(Be,Qe)|0,d=d+Math.imul(je,Je)|0,E=E+Math.imul(je,Qe)|0,b=b+Math.imul(Le,Ze)|0,d=d+Math.imul(Le,et)|0,d=d+Math.imul(De,Ze)|0,E=E+Math.imul(De,et)|0,b=b+Math.imul(Ie,tt)|0,d=d+Math.imul(Ie,rt)|0,d=d+Math.imul(Ne,tt)|0,E=E+Math.imul(Ne,rt)|0,b=b+Math.imul(re,nt)|0,d=d+Math.imul(re,it)|0,d=d+Math.imul(Me,nt)|0,E=E+Math.imul(Me,it)|0,b=b+Math.imul(K,st)|0,d=d+Math.imul(K,ot)|0,d=d+Math.imul(z,st)|0,E=E+Math.imul(z,ot)|0;var mp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(mp>>>26)|0,mp&=67108863,b=Math.imul(Fe,Je),d=Math.imul(Fe,Qe),d=d+Math.imul($e,Je)|0,E=Math.imul($e,Qe),b=b+Math.imul(Be,Ze)|0,d=d+Math.imul(Be,et)|0,d=d+Math.imul(je,Ze)|0,E=E+Math.imul(je,et)|0,b=b+Math.imul(Le,tt)|0,d=d+Math.imul(Le,rt)|0,d=d+Math.imul(De,tt)|0,E=E+Math.imul(De,rt)|0,b=b+Math.imul(Ie,nt)|0,d=d+Math.imul(Ie,it)|0,d=d+Math.imul(Ne,nt)|0,E=E+Math.imul(Ne,it)|0,b=b+Math.imul(re,st)|0,d=d+Math.imul(re,ot)|0,d=d+Math.imul(Me,st)|0,E=E+Math.imul(Me,ot)|0;var gp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(gp>>>26)|0,gp&=67108863,b=Math.imul(Fe,Ze),d=Math.imul(Fe,et),d=d+Math.imul($e,Ze)|0,E=Math.imul($e,et),b=b+Math.imul(Be,tt)|0,d=d+Math.imul(Be,rt)|0,d=d+Math.imul(je,tt)|0,E=E+Math.imul(je,rt)|0,b=b+Math.imul(Le,nt)|0,d=d+Math.imul(Le,it)|0,d=d+Math.imul(De,nt)|0,E=E+Math.imul(De,it)|0,b=b+Math.imul(Ie,st)|0,d=d+Math.imul(Ie,ot)|0,d=d+Math.imul(Ne,st)|0,E=E+Math.imul(Ne,ot)|0;var vp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(vp>>>26)|0,vp&=67108863,b=Math.imul(Fe,tt),d=Math.imul(Fe,rt),d=d+Math.imul($e,tt)|0,E=Math.imul($e,rt),b=b+Math.imul(Be,nt)|0,d=d+Math.imul(Be,it)|0,d=d+Math.imul(je,nt)|0,E=E+Math.imul(je,it)|0,b=b+Math.imul(Le,st)|0,d=d+Math.imul(Le,ot)|0,d=d+Math.imul(De,st)|0,E=E+Math.imul(De,ot)|0;var xp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(xp>>>26)|0,xp&=67108863,b=Math.imul(Fe,nt),d=Math.imul(Fe,it),d=d+Math.imul($e,nt)|0,E=Math.imul($e,it),b=b+Math.imul(Be,st)|0,d=d+Math.imul(Be,ot)|0,d=d+Math.imul(je,st)|0,E=E+Math.imul(je,ot)|0;var yp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(yp>>>26)|0,yp&=67108863,b=Math.imul(Fe,st),d=Math.imul(Fe,ot),d=d+Math.imul($e,st)|0,E=Math.imul($e,ot);var _p=(C+b|0)+((d&8191)<<13)|0;return C=(E+(d>>>13)|0)+(_p>>>26)|0,_p&=67108863,v[0]=rp,v[1]=np,v[2]=ip,v[3]=sp,v[4]=op,v[5]=ap,v[6]=cp,v[7]=lp,v[8]=up,v[9]=pp,v[10]=fp,v[11]=dp,v[12]=hp,v[13]=mp,v[14]=gp,v[15]=vp,v[16]=xp,v[17]=yp,v[18]=_p,C!==0&&(v[19]=C,x.length++),x};Math.imul||(_=y);function S(T,l,h){h.negative=l.negative^T.negative,h.length=T.length+l.length;for(var x=0,w=0,g=0;g<h.length-1;g++){var v=w;w=0;for(var C=x&67108863,b=Math.min(g,l.length-1),d=Math.max(0,g-T.length+1);d<=b;d++){var E=g-d,U=T.words[E]|0,I=l.words[d]|0,D=U*I,H=D&67108863;v=v+(D/67108864|0)|0,H=H+C|0,C=H&67108863,v=v+(H>>>26)|0,w+=v>>>26,v&=67108863}h.words[g]=C,x=v,v=w}return x!==0?h.words[g]=x:h.length--,h.strip()}function A(T,l,h){var x=new P;return x.mulp(T,l,h)}i.prototype.mulTo=function(l,h){var x,w=this.length+l.length;return this.length===10&&l.length===10?x=_(this,l,h):w<63?x=y(this,l,h):w<1024?x=S(this,l,h):x=A(this,l,h),x};function P(T,l){this.x=T,this.y=l}P.prototype.makeRBT=function(l){for(var h=new Array(l),x=i.prototype._countBits(l)-1,w=0;w<l;w++)h[w]=this.revBin(w,x,l);return h},P.prototype.revBin=function(l,h,x){if(l===0||l===x-1)return l;for(var w=0,g=0;g<h;g++)w|=(l&1)<<h-g-1,l>>=1;return w},P.prototype.permute=function(l,h,x,w,g,v){for(var C=0;C<v;C++)w[C]=h[l[C]],g[C]=x[l[C]]},P.prototype.transform=function(l,h,x,w,g,v){this.permute(v,l,h,x,w,g);for(var C=1;C<g;C<<=1)for(var b=C<<1,d=Math.cos(2*Math.PI/b),E=Math.sin(2*Math.PI/b),U=0;U<g;U+=b)for(var I=d,D=E,H=0;H<C;H++){var V=x[U+H],B=w[U+H],me=x[U+H+C],ie=w[U+H+C],R=I*me-D*ie;ie=I*ie+D*me,me=R,x[U+H]=V+me,w[U+H]=B+ie,x[U+H+C]=V-me,w[U+H+C]=B-ie,H!==b&&(R=d*I-E*D,D=d*D+E*I,I=R)}},P.prototype.guessLen13b=function(l,h){var x=Math.max(h,l)|1,w=x&1,g=0;for(x=x/2|0;x;x=x>>>1)g++;return 1<<g+1+w},P.prototype.conjugate=function(l,h,x){if(!(x<=1))for(var w=0;w<x/2;w++){var g=l[w];l[w]=l[x-w-1],l[x-w-1]=g,g=h[w],h[w]=-h[x-w-1],h[x-w-1]=-g}},P.prototype.normalize13b=function(l,h){for(var x=0,w=0;w<h/2;w++){var g=Math.round(l[2*w+1]/h)*8192+Math.round(l[2*w]/h)+x;l[w]=g&67108863,g<67108864?x=0:x=g/67108864|0}return l},P.prototype.convert13b=function(l,h,x,w){for(var g=0,v=0;v<h;v++)g=g+(l[v]|0),x[2*v]=g&8191,g=g>>>13,x[2*v+1]=g&8191,g=g>>>13;for(v=2*h;v<w;++v)x[v]=0;t(g===0),t((g&-8192)===0)},P.prototype.stub=function(l){for(var h=new Array(l),x=0;x<l;x++)h[x]=0;return h},P.prototype.mulp=function(l,h,x){var w=2*this.guessLen13b(l.length,h.length),g=this.makeRBT(w),v=this.stub(w),C=new Array(w),b=new Array(w),d=new Array(w),E=new Array(w),U=new Array(w),I=new Array(w),D=x.words;D.length=w,this.convert13b(l.words,l.length,C,w),this.convert13b(h.words,h.length,E,w),this.transform(C,v,b,d,w,g),this.transform(E,v,U,I,w,g);for(var H=0;H<w;H++){var V=b[H]*U[H]-d[H]*I[H];d[H]=b[H]*I[H]+d[H]*U[H],b[H]=V}return this.conjugate(b,d,w),this.transform(b,d,D,v,w,g),this.conjugate(D,v,w),this.normalize13b(D,w),x.negative=l.negative^h.negative,x.length=l.length+h.length,x.strip()},i.prototype.mul=function(l){var h=new i(null);return h.words=new Array(this.length+l.length),this.mulTo(l,h)},i.prototype.mulf=function(l){var h=new i(null);return h.words=new Array(this.length+l.length),A(this,l,h)},i.prototype.imul=function(l){return this.clone().mulTo(l,this)},i.prototype.imuln=function(l){t(typeof l=="number"),t(l<67108864);for(var h=0,x=0;x<this.length;x++){var w=(this.words[x]|0)*l,g=(w&67108863)+(h&67108863);h>>=26,h+=w/67108864|0,h+=g>>>26,this.words[x]=g&67108863}return h!==0&&(this.words[x]=h,this.length++),this.length=l===0?1:this.length,this},i.prototype.muln=function(l){return this.clone().imuln(l)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(l){var h=m(l);if(h.length===0)return new i(1);for(var x=this,w=0;w<h.length&&h[w]===0;w++,x=x.sqr());if(++w<h.length)for(var g=x.sqr();w<h.length;w++,g=g.sqr())h[w]!==0&&(x=x.mul(g));return x},i.prototype.iushln=function(l){t(typeof l=="number"&&l>=0);var h=l%26,x=(l-h)/26,w=67108863>>>26-h<<26-h,g;if(h!==0){var v=0;for(g=0;g<this.length;g++){var C=this.words[g]&w,b=(this.words[g]|0)-C<<h;this.words[g]=b|v,v=C>>>26-h}v&&(this.words[g]=v,this.length++)}if(x!==0){for(g=this.length-1;g>=0;g--)this.words[g+x]=this.words[g];for(g=0;g<x;g++)this.words[g]=0;this.length+=x}return this.strip()},i.prototype.ishln=function(l){return t(this.negative===0),this.iushln(l)},i.prototype.iushrn=function(l,h,x){t(typeof l=="number"&&l>=0);var w;h?w=(h-h%26)/26:w=0;var g=l%26,v=Math.min((l-g)/26,this.length),C=67108863^67108863>>>g<<g,b=x;if(w-=v,w=Math.max(0,w),b){for(var d=0;d<v;d++)b.words[d]=this.words[d];b.length=v}if(v!==0)if(this.length>v)for(this.length-=v,d=0;d<this.length;d++)this.words[d]=this.words[d+v];else this.words[0]=0,this.length=1;var E=0;for(d=this.length-1;d>=0&&(E!==0||d>=w);d--){var U=this.words[d]|0;this.words[d]=E<<26-g|U>>>g,E=U&C}return b&&E!==0&&(b.words[b.length++]=E),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(l,h,x){return t(this.negative===0),this.iushrn(l,h,x)},i.prototype.shln=function(l){return this.clone().ishln(l)},i.prototype.ushln=function(l){return this.clone().iushln(l)},i.prototype.shrn=function(l){return this.clone().ishrn(l)},i.prototype.ushrn=function(l){return this.clone().iushrn(l)},i.prototype.testn=function(l){t(typeof l=="number"&&l>=0);var h=l%26,x=(l-h)/26,w=1<<h;if(this.length<=x)return!1;var g=this.words[x];return!!(g&w)},i.prototype.imaskn=function(l){t(typeof l=="number"&&l>=0);var h=l%26,x=(l-h)/26;if(t(this.negative===0,"imaskn works only with positive numbers"),this.length<=x)return this;if(h!==0&&x++,this.length=Math.min(x,this.length),h!==0){var w=67108863^67108863>>>h<<h;this.words[this.length-1]&=w}return this.length===0&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.maskn=function(l){return this.clone().imaskn(l)},i.prototype.iaddn=function(l){return t(typeof l=="number"),t(l<67108864),l<0?this.isubn(-l):this.negative!==0?this.length===1&&(this.words[0]|0)<l?(this.words[0]=l-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(l),this.negative=1,this):this._iaddn(l)},i.prototype._iaddn=function(l){this.words[0]+=l;for(var h=0;h<this.length&&this.words[h]>=67108864;h++)this.words[h]-=67108864,h===this.length-1?this.words[h+1]=1:this.words[h+1]++;return this.length=Math.max(this.length,h+1),this},i.prototype.isubn=function(l){if(t(typeof l=="number"),t(l<67108864),l<0)return this.iaddn(-l);if(this.negative!==0)return this.negative=0,this.iaddn(l),this.negative=1,this;if(this.words[0]-=l,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var h=0;h<this.length&&this.words[h]<0;h++)this.words[h]+=67108864,this.words[h+1]-=1;return this.strip()},i.prototype.addn=function(l){return this.clone().iaddn(l)},i.prototype.subn=function(l){return this.clone().isubn(l)},i.prototype.iabs=function(){return this.negative=0,this},i.prototype.abs=function(){return this.clone().iabs()},i.prototype._ishlnsubmul=function(l,h,x){var w=l.length+x,g;this._expand(w);var v,C=0;for(g=0;g<l.length;g++){v=(this.words[g+x]|0)+C;var b=(l.words[g]|0)*h;v-=b&67108863,C=(v>>26)-(b/67108864|0),this.words[g+x]=v&67108863}for(;g<this.length-x;g++)v=(this.words[g+x]|0)+C,C=v>>26,this.words[g+x]=v&67108863;if(C===0)return this.strip();for(t(C===-1),C=0,g=0;g<this.length;g++)v=-(this.words[g]|0)+C,C=v>>26,this.words[g]=v&67108863;return this.negative=1,this.strip()},i.prototype._wordDiv=function(l,h){var x=this.length-l.length,w=this.clone(),g=l,v=g.words[g.length-1]|0,C=this._countBits(v);x=26-C,x!==0&&(g=g.ushln(x),w.iushln(x),v=g.words[g.length-1]|0);var b=w.length-g.length,d;if(h!=="mod"){d=new i(null),d.length=b+1,d.words=new Array(d.length);for(var E=0;E<d.length;E++)d.words[E]=0}var U=w.clone()._ishlnsubmul(g,1,b);U.negative===0&&(w=U,d&&(d.words[b]=1));for(var I=b-1;I>=0;I--){var D=(w.words[g.length+I]|0)*67108864+(w.words[g.length+I-1]|0);for(D=Math.min(D/v|0,67108863),w._ishlnsubmul(g,D,I);w.negative!==0;)D--,w.negative=0,w._ishlnsubmul(g,1,I),w.isZero()||(w.negative^=1);d&&(d.words[I]=D)}return d&&d.strip(),w.strip(),h!=="div"&&x!==0&&w.iushrn(x),{div:d||null,mod:w}},i.prototype.divmod=function(l,h,x){if(t(!l.isZero()),this.isZero())return{div:new i(0),mod:new i(0)};var w,g,v;return this.negative!==0&&l.negative===0?(v=this.neg().divmod(l,h),h!=="mod"&&(w=v.div.neg()),h!=="div"&&(g=v.mod.neg(),x&&g.negative!==0&&g.iadd(l)),{div:w,mod:g}):this.negative===0&&l.negative!==0?(v=this.divmod(l.neg(),h),h!=="mod"&&(w=v.div.neg()),{div:w,mod:v.mod}):(this.negative&l.negative)!==0?(v=this.neg().divmod(l.neg(),h),h!=="div"&&(g=v.mod.neg(),x&&g.negative!==0&&g.isub(l)),{div:v.div,mod:g}):l.length>this.length||this.cmp(l)<0?{div:new i(0),mod:this}:l.length===1?h==="div"?{div:this.divn(l.words[0]),mod:null}:h==="mod"?{div:null,mod:new i(this.modn(l.words[0]))}:{div:this.divn(l.words[0]),mod:new i(this.modn(l.words[0]))}:this._wordDiv(l,h)},i.prototype.div=function(l){return this.divmod(l,"div",!1).div},i.prototype.mod=function(l){return this.divmod(l,"mod",!1).mod},i.prototype.umod=function(l){return this.divmod(l,"mod",!0).mod},i.prototype.divRound=function(l){var h=this.divmod(l);if(h.mod.isZero())return h.div;var x=h.div.negative!==0?h.mod.isub(l):h.mod,w=l.ushrn(1),g=l.andln(1),v=x.cmp(w);return v<0||g===1&&v===0?h.div:h.div.negative!==0?h.div.isubn(1):h.div.iaddn(1)},i.prototype.modn=function(l){t(l<=67108863);for(var h=(1<<26)%l,x=0,w=this.length-1;w>=0;w--)x=(h*x+(this.words[w]|0))%l;return x},i.prototype.idivn=function(l){t(l<=67108863);for(var h=0,x=this.length-1;x>=0;x--){var w=(this.words[x]|0)+h*67108864;this.words[x]=w/l|0,h=w%l}return this.strip()},i.prototype.divn=function(l){return this.clone().idivn(l)},i.prototype.egcd=function(l){t(l.negative===0),t(!l.isZero());var h=this,x=l.clone();h.negative!==0?h=h.umod(l):h=h.clone();for(var w=new i(1),g=new i(0),v=new i(0),C=new i(1),b=0;h.isEven()&&x.isEven();)h.iushrn(1),x.iushrn(1),++b;for(var d=x.clone(),E=h.clone();!h.isZero();){for(var U=0,I=1;(h.words[0]&I)===0&&U<26;++U,I<<=1);if(U>0)for(h.iushrn(U);U-- >0;)(w.isOdd()||g.isOdd())&&(w.iadd(d),g.isub(E)),w.iushrn(1),g.iushrn(1);for(var D=0,H=1;(x.words[0]&H)===0&&D<26;++D,H<<=1);if(D>0)for(x.iushrn(D);D-- >0;)(v.isOdd()||C.isOdd())&&(v.iadd(d),C.isub(E)),v.iushrn(1),C.iushrn(1);h.cmp(x)>=0?(h.isub(x),w.isub(v),g.isub(C)):(x.isub(h),v.isub(w),C.isub(g))}return{a:v,b:C,gcd:x.iushln(b)}},i.prototype._invmp=function(l){t(l.negative===0),t(!l.isZero());var h=this,x=l.clone();h.negative!==0?h=h.umod(l):h=h.clone();for(var w=new i(1),g=new i(0),v=x.clone();h.cmpn(1)>0&&x.cmpn(1)>0;){for(var C=0,b=1;(h.words[0]&b)===0&&C<26;++C,b<<=1);if(C>0)for(h.iushrn(C);C-- >0;)w.isOdd()&&w.iadd(v),w.iushrn(1);for(var d=0,E=1;(x.words[0]&E)===0&&d<26;++d,E<<=1);if(d>0)for(x.iushrn(d);d-- >0;)g.isOdd()&&g.iadd(v),g.iushrn(1);h.cmp(x)>=0?(h.isub(x),w.isub(g)):(x.isub(h),g.isub(w))}var U;return h.cmpn(1)===0?U=w:U=g,U.cmpn(0)<0&&U.iadd(l),U},i.prototype.gcd=function(l){if(this.isZero())return l.abs();if(l.isZero())return this.abs();var h=this.clone(),x=l.clone();h.negative=0,x.negative=0;for(var w=0;h.isEven()&&x.isEven();w++)h.iushrn(1),x.iushrn(1);do{for(;h.isEven();)h.iushrn(1);for(;x.isEven();)x.iushrn(1);var g=h.cmp(x);if(g<0){var v=h;h=x,x=v}else if(g===0||x.cmpn(1)===0)break;h.isub(x)}while(!0);return x.iushln(w)},i.prototype.invm=function(l){return this.egcd(l).a.umod(l)},i.prototype.isEven=function(){return(this.words[0]&1)===0},i.prototype.isOdd=function(){return(this.words[0]&1)===1},i.prototype.andln=function(l){return this.words[0]&l},i.prototype.bincn=function(l){t(typeof l=="number");var h=l%26,x=(l-h)/26,w=1<<h;if(this.length<=x)return this._expand(x+1),this.words[x]|=w,this;for(var g=w,v=x;g!==0&&v<this.length;v++){var C=this.words[v]|0;C+=g,g=C>>>26,C&=67108863,this.words[v]=C}return g!==0&&(this.words[v]=g,this.length++),this},i.prototype.isZero=function(){return this.length===1&&this.words[0]===0},i.prototype.cmpn=function(l){var h=l<0;if(this.negative!==0&&!h)return-1;if(this.negative===0&&h)return 1;this.strip();var x;if(this.length>1)x=1;else{h&&(l=-l),t(l<=67108863,"Number is too big");var w=this.words[0]|0;x=w===l?0:w<l?-1:1}return this.negative!==0?-x|0:x},i.prototype.cmp=function(l){if(this.negative!==0&&l.negative===0)return-1;if(this.negative===0&&l.negative!==0)return 1;var h=this.ucmp(l);return this.negative!==0?-h|0:h},i.prototype.ucmp=function(l){if(this.length>l.length)return 1;if(this.length<l.length)return-1;for(var h=0,x=this.length-1;x>=0;x--){var w=this.words[x]|0,g=l.words[x]|0;if(w!==g){w<g?h=-1:w>g&&(h=1);break}}return h},i.prototype.gtn=function(l){return this.cmpn(l)===1},i.prototype.gt=function(l){return this.cmp(l)===1},i.prototype.gten=function(l){return this.cmpn(l)>=0},i.prototype.gte=function(l){return this.cmp(l)>=0},i.prototype.ltn=function(l){return this.cmpn(l)===-1},i.prototype.lt=function(l){return this.cmp(l)===-1},i.prototype.lten=function(l){return this.cmpn(l)<=0},i.prototype.lte=function(l){return this.cmp(l)<=0},i.prototype.eqn=function(l){return this.cmpn(l)===0},i.prototype.eq=function(l){return this.cmp(l)===0},i.red=function(l){return new M(l)},i.prototype.toRed=function(l){return t(!this.red,"Already a number in reduction context"),t(this.negative===0,"red works only with positives"),l.convertTo(this)._forceRed(l)},i.prototype.fromRed=function(){return t(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(l){return this.red=l,this},i.prototype.forceRed=function(l){return t(!this.red,"Already a number in reduction context"),this._forceRed(l)},i.prototype.redAdd=function(l){return t(this.red,"redAdd works only with red numbers"),this.red.add(this,l)},i.prototype.redIAdd=function(l){return t(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,l)},i.prototype.redSub=function(l){return t(this.red,"redSub works only with red numbers"),this.red.sub(this,l)},i.prototype.redISub=function(l){return t(this.red,"redISub works only with red numbers"),this.red.isub(this,l)},i.prototype.redShl=function(l){return t(this.red,"redShl works only with red numbers"),this.red.shl(this,l)},i.prototype.redMul=function(l){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.mul(this,l)},i.prototype.redIMul=function(l){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.imul(this,l)},i.prototype.redSqr=function(){return t(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return t(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return t(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return t(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return t(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(l){return t(this.red&&!l.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,l)};var L={k256:null,p224:null,p192:null,p25519:null};function N(T,l){this.name=T,this.p=new i(l,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}N.prototype._tmp=function(){var l=new i(null);return l.words=new Array(Math.ceil(this.n/13)),l},N.prototype.ireduce=function(l){var h=l,x;do this.split(h,this.tmp),h=this.imulK(h),h=h.iadd(this.tmp),x=h.bitLength();while(x>this.n);var w=x<this.n?-1:h.ucmp(this.p);return w===0?(h.words[0]=0,h.length=1):w>0?h.isub(this.p):h.strip!==void 0?h.strip():h._strip(),h},N.prototype.split=function(l,h){l.iushrn(this.n,0,h)},N.prototype.imulK=function(l){return l.imul(this.k)};function $(){N.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n($,N),$.prototype.split=function(l,h){for(var x=4194303,w=Math.min(l.length,9),g=0;g<w;g++)h.words[g]=l.words[g];if(h.length=w,l.length<=9){l.words[0]=0,l.length=1;return}var v=l.words[9];for(h.words[h.length++]=v&x,g=10;g<l.length;g++){var C=l.words[g]|0;l.words[g-10]=(C&x)<<4|v>>>22,v=C}v>>>=22,l.words[g-10]=v,v===0&&l.length>10?l.length-=10:l.length-=9},$.prototype.imulK=function(l){l.words[l.length]=0,l.words[l.length+1]=0,l.length+=2;for(var h=0,x=0;x<l.length;x++){var w=l.words[x]|0;h+=w*977,l.words[x]=h&67108863,h=w*64+(h/67108864|0)}return l.words[l.length-1]===0&&(l.length--,l.words[l.length-1]===0&&l.length--),l};function W(){N.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(W,N);function q(){N.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(q,N);function G(){N.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(G,N),G.prototype.imulK=function(l){for(var h=0,x=0;x<l.length;x++){var w=(l.words[x]|0)*19+h,g=w&67108863;w>>>=26,l.words[x]=g,h=w}return h!==0&&(l.words[l.length++]=h),l},i._prime=function(l){if(L[l])return L[l];var h;if(l==="k256")h=new $;else if(l==="p224")h=new W;else if(l==="p192")h=new q;else if(l==="p25519")h=new G;else throw new Error("Unknown prime "+l);return L[l]=h,h};function M(T){if(typeof T=="string"){var l=i._prime(T);this.m=l.p,this.prime=l}else t(T.gtn(1),"modulus must be greater than 1"),this.m=T,this.prime=null}M.prototype._verify1=function(l){t(l.negative===0,"red works only with positives"),t(l.red,"red works only with red numbers")},M.prototype._verify2=function(l,h){t((l.negative|h.negative)===0,"red works only with positives"),t(l.red&&l.red===h.red,"red works only with red numbers")},M.prototype.imod=function(l){return this.prime?this.prime.ireduce(l)._forceRed(this):l.umod(this.m)._forceRed(this)},M.prototype.neg=function(l){return l.isZero()?l.clone():this.m.sub(l)._forceRed(this)},M.prototype.add=function(l,h){this._verify2(l,h);var x=l.add(h);return x.cmp(this.m)>=0&&x.isub(this.m),x._forceRed(this)},M.prototype.iadd=function(l,h){this._verify2(l,h);var x=l.iadd(h);return x.cmp(this.m)>=0&&x.isub(this.m),x},M.prototype.sub=function(l,h){this._verify2(l,h);var x=l.sub(h);return x.cmpn(0)<0&&x.iadd(this.m),x._forceRed(this)},M.prototype.isub=function(l,h){this._verify2(l,h);var x=l.isub(h);return x.cmpn(0)<0&&x.iadd(this.m),x},M.prototype.shl=function(l,h){return this._verify1(l),this.imod(l.ushln(h))},M.prototype.imul=function(l,h){return this._verify2(l,h),this.imod(l.imul(h))},M.prototype.mul=function(l,h){return this._verify2(l,h),this.imod(l.mul(h))},M.prototype.isqr=function(l){return this.imul(l,l.clone())},M.prototype.sqr=function(l){return this.mul(l,l)},M.prototype.sqrt=function(l){if(l.isZero())return l.clone();var h=this.m.andln(3);if(t(h%2===1),h===3){var x=this.m.add(new i(1)).iushrn(2);return this.pow(l,x)}for(var w=this.m.subn(1),g=0;!w.isZero()&&w.andln(1)===0;)g++,w.iushrn(1);t(!w.isZero());var v=new i(1).toRed(this),C=v.redNeg(),b=this.m.subn(1).iushrn(1),d=this.m.bitLength();for(d=new i(2*d*d).toRed(this);this.pow(d,b).cmp(C)!==0;)d.redIAdd(C);for(var E=this.pow(d,w),U=this.pow(l,w.addn(1).iushrn(1)),I=this.pow(l,w),D=g;I.cmp(v)!==0;){for(var H=I,V=0;H.cmp(v)!==0;V++)H=H.redSqr();t(V<D);var B=this.pow(E,new i(1).iushln(D-V-1));U=U.redMul(B),E=B.redSqr(),I=I.redMul(E),D=V}return U},M.prototype.invm=function(l){var h=l._invmp(this.m);return h.negative!==0?(h.negative=0,this.imod(h).redNeg()):this.imod(h)},M.prototype.pow=function(l,h){if(h.isZero())return new i(1).toRed(this);if(h.cmpn(1)===0)return l.clone();var x=4,w=new Array(1<<x);w[0]=new i(1).toRed(this),w[1]=l;for(var g=2;g<w.length;g++)w[g]=this.mul(w[g-1],l);var v=w[0],C=0,b=0,d=h.bitLength()%26;for(d===0&&(d=26),g=h.length-1;g>=0;g--){for(var E=h.words[g],U=d-1;U>=0;U--){var I=E>>U&1;if(v!==w[0]&&(v=this.sqr(v)),I===0&&C===0){b=0;continue}C<<=1,C|=I,b++,!(b!==x&&(g!==0||U!==0))&&(v=this.mul(v,w[C]),b=0,C=0)}d=26}return v},M.prototype.convertTo=function(l){var h=l.umod(this.m);return h===l?h.clone():h},M.prototype.convertFrom=function(l){var h=l.clone();return h.red=null,h},i.mont=function(l){return new F(l)};function F(T){M.call(this,T),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new i(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}n(F,M),F.prototype.convertTo=function(l){return this.imod(l.ushln(this.shift))},F.prototype.convertFrom=function(l){var h=this.imod(l.mul(this.rinv));return h.red=null,h},F.prototype.imul=function(l,h){if(l.isZero()||h.isZero())return l.words[0]=0,l.length=1,l;var x=l.imul(h),w=x.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),g=x.isub(w).iushrn(this.shift),v=g;return g.cmp(this.m)>=0?v=g.isub(this.m):g.cmpn(0)<0&&(v=g.iadd(this.m)),v._forceRed(this)},F.prototype.mul=function(l,h){if(l.isZero()||h.isZero())return new i(0)._forceRed(this);var x=l.mul(h),w=x.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),g=x.isub(w).iushrn(this.shift),v=g;return g.cmp(this.m)>=0?v=g.isub(this.m):g.cmpn(0)<0&&(v=g.iadd(this.m)),v._forceRed(this)},F.prototype.invm=function(l){var h=this.imod(l._invmp(this.m).mul(this.r2));return h._forceRed(this)}})(typeof jh>"u"||jh,cE)});var lE=O((wG,$h)=>{typeof Object.create=="function"?$h.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:$h.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}});var Gn=O((SG,Uh)=>{try{if(Hh=require("util"),typeof Hh.inherits!="function")throw"";Uh.exports=Hh.inherits}catch{Uh.exports=lE()}var Hh});var Gl=O((EG,uE)=>{"use strict";var Wl=require("buffer"),As=Wl.Buffer,pr={},fr;for(fr in Wl)Wl.hasOwnProperty(fr)&&(fr==="SlowBuffer"||fr==="Buffer"||(pr[fr]=Wl[fr]));var Rs=pr.Buffer={};for(fr in As)As.hasOwnProperty(fr)&&(fr==="allocUnsafe"||fr==="allocUnsafeSlow"||(Rs[fr]=As[fr]));pr.Buffer.prototype=As.prototype;(!Rs.from||Rs.from===Uint8Array.from)&&(Rs.from=function(r,e,t){if(typeof r=="number")throw new TypeError('The "value" argument must not be of type number. Received type '+typeof r);if(r&&typeof r.length>"u")throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r);return As(r,e,t)});Rs.alloc||(Rs.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError('The "size" argument must be of type number. Received type '+typeof r);if(r<0||r>=2*(1<<30))throw new RangeError('The value "'+r+'" is invalid for option "size"');var n=As(r);return!e||e.length===0?n.fill(0):typeof t=="string"?n.fill(e,t):n.fill(e),n});if(!pr.kStringMaxLength)try{pr.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch{}pr.constants||(pr.constants={MAX_LENGTH:pr.kMaxLength},pr.kStringMaxLength&&(pr.constants.MAX_STRING_LENGTH=pr.kStringMaxLength));uE.exports=pr});var zl=O(pE=>{"use strict";var oj=Gn();function dr(r){this._reporterState={obj:null,path:[],options:r||{},errors:[]}}pE.Reporter=dr;dr.prototype.isError=function(e){return e instanceof ks};dr.prototype.save=function(){let e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}};dr.prototype.restore=function(e){let t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)};dr.prototype.enterKey=function(e){return this._reporterState.path.push(e)};dr.prototype.exitKey=function(e){let t=this._reporterState;t.path=t.path.slice(0,e-1)};dr.prototype.leaveKey=function(e,t,n){let i=this._reporterState;this.exitKey(e),i.obj!==null&&(i.obj[t]=n)};dr.prototype.path=function(){return this._reporterState.path.join("/")};dr.prototype.enterObject=function(){let e=this._reporterState,t=e.obj;return e.obj={},t};dr.prototype.leaveObject=function(e){let t=this._reporterState,n=t.obj;return t.obj=e,n};dr.prototype.error=function(e){let t,n=this._reporterState,i=e instanceof ks;if(i?t=e:t=new ks(n.path.map(function(s){return"["+JSON.stringify(s)+"]"}).join(""),e.message||e,e.stack),!n.options.partial)throw t;return i||n.errors.push(t),t};dr.prototype.wrapResult=function(e){let t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e};function ks(r,e){this.path=r,this.rethrow(e)}oj(ks,Error);ks.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,ks),!this.stack)try{throw new Error(this.message)}catch(t){this.stack=t.stack}return this}});var Ms=O(qh=>{"use strict";var aj=Gn(),Vl=zl().Reporter,Os=Gl().Buffer;function hr(r,e){if(Vl.call(this,e),!Os.isBuffer(r)){this.error("Input not Buffer");return}this.base=r,this.offset=0,this.length=r.length}aj(hr,Vl);qh.DecoderBuffer=hr;hr.isDecoderBuffer=function(e){return e instanceof hr?!0:typeof e=="object"&&Os.isBuffer(e.base)&&e.constructor.name==="DecoderBuffer"&&typeof e.offset=="number"&&typeof e.length=="number"&&typeof e.save=="function"&&typeof e.restore=="function"&&typeof e.isEmpty=="function"&&typeof e.readUInt8=="function"&&typeof e.skip=="function"&&typeof e.raw=="function"};hr.prototype.save=function(){return{offset:this.offset,reporter:Vl.prototype.save.call(this)}};hr.prototype.restore=function(e){let t=new hr(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,Vl.prototype.restore.call(this,e.reporter),t};hr.prototype.isEmpty=function(){return this.offset===this.length};hr.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")};hr.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");let n=new hr(this.base);return n._reporterState=this._reporterState,n.offset=this.offset,n.length=this.offset+e,this.offset+=e,n};hr.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)};function Ps(r,e){if(Array.isArray(r))this.length=0,this.value=r.map(function(t){return Ps.isEncoderBuffer(t)||(t=new Ps(t,e)),this.length+=t.length,t},this);else if(typeof r=="number"){if(!(0<=r&&r<=255))return e.error("non-byte EncoderBuffer value");this.value=r,this.length=1}else if(typeof r=="string")this.value=r,this.length=Os.byteLength(r);else if(Os.isBuffer(r))this.value=r,this.length=r.length;else return e.error("Unsupported type: "+typeof r)}qh.EncoderBuffer=Ps;Ps.isEncoderBuffer=function(e){return e instanceof Ps?!0:typeof e=="object"&&e.constructor.name==="EncoderBuffer"&&typeof e.length=="number"&&typeof e.join=="function"};Ps.prototype.join=function(e,t){return e||(e=Os.alloc(this.length)),t||(t=0),this.length===0||(Array.isArray(this.value)?this.value.forEach(function(n){n.join(e,t),t+=n.length}):(typeof this.value=="number"?e[t]=this.value:typeof this.value=="string"?e.write(this.value,t):Os.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length)),e}});var hE=O((AG,dE)=>{dE.exports=fE;function fE(r,e){if(!r)throw new Error(e||"Assertion failed")}fE.equal=function(e,t,n){if(e!=t)throw new Error(n||"Assertion failed: "+e+" != "+t)}});var Kl=O((RG,gE)=>{"use strict";var cj=zl().Reporter,lj=Ms().EncoderBuffer,uj=Ms().DecoderBuffer,Pt=hE(),mE=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],pj=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(mE),fj=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function fe(r,e,t){let n={};this._baseState=n,n.name=t,n.enc=r,n.parent=e||null,n.children=null,n.tag=null,n.args=null,n.reverseArgs=null,n.choice=null,n.optional=!1,n.any=!1,n.obj=!1,n.use=null,n.useDecoder=null,n.key=null,n.default=null,n.explicit=null,n.implicit=null,n.contains=null,n.parent||(n.children=[],this._wrap())}gE.exports=fe;var dj=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];fe.prototype.clone=function(){let e=this._baseState,t={};dj.forEach(function(i){t[i]=e[i]});let n=new this.constructor(t.parent);return n._baseState=t,n};fe.prototype._wrap=function(){let e=this._baseState;pj.forEach(function(t){this[t]=function(){let i=new this.constructor(this);return e.children.push(i),i[t].apply(i,arguments)}},this)};fe.prototype._init=function(e){let t=this._baseState;Pt(t.parent===null),e.call(this),t.children=t.children.filter(function(n){return n._baseState.parent===this},this),Pt.equal(t.children.length,1,"Root node can have only one child")};fe.prototype._useArgs=function(e){let t=this._baseState,n=e.filter(function(i){return i instanceof this.constructor},this);e=e.filter(function(i){return!(i instanceof this.constructor)},this),n.length!==0&&(Pt(t.children===null),t.children=n,n.forEach(function(i){i._baseState.parent=this},this)),e.length!==0&&(Pt(t.args===null),t.args=e,t.reverseArgs=e.map(function(i){if(typeof i!="object"||i.constructor!==Object)return i;let s={};return Object.keys(i).forEach(function(o){o==(o|0)&&(o|=0);let a=i[o];s[a]=o}),s}))};fj.forEach(function(r){fe.prototype[r]=function(){let t=this._baseState;throw new Error(r+" not implemented for encoding: "+t.enc)}});mE.forEach(function(r){fe.prototype[r]=function(){let t=this._baseState,n=Array.prototype.slice.call(arguments);return Pt(t.tag===null),t.tag=r,this._useArgs(n),this}});fe.prototype.use=function(e){Pt(e);let t=this._baseState;return Pt(t.use===null),t.use=e,this};fe.prototype.optional=function(){let e=this._baseState;return e.optional=!0,this};fe.prototype.def=function(e){let t=this._baseState;return Pt(t.default===null),t.default=e,t.optional=!0,this};fe.prototype.explicit=function(e){let t=this._baseState;return Pt(t.explicit===null&&t.implicit===null),t.explicit=e,this};fe.prototype.implicit=function(e){let t=this._baseState;return Pt(t.explicit===null&&t.implicit===null),t.implicit=e,this};fe.prototype.obj=function(){let e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,t.length!==0&&this._useArgs(t),this};fe.prototype.key=function(e){let t=this._baseState;return Pt(t.key===null),t.key=e,this};fe.prototype.any=function(){let e=this._baseState;return e.any=!0,this};fe.prototype.choice=function(e){let t=this._baseState;return Pt(t.choice===null),t.choice=e,this._useArgs(Object.keys(e).map(function(n){return e[n]})),this};fe.prototype.contains=function(e){let t=this._baseState;return Pt(t.use===null),t.contains=e,this};fe.prototype._decode=function(e,t){let n=this._baseState;if(n.parent===null)return e.wrapResult(n.children[0]._decode(e,t));let i=n.default,s=!0,o=null;if(n.key!==null&&(o=e.enterKey(n.key)),n.optional){let c=null;if(n.explicit!==null?c=n.explicit:n.implicit!==null?c=n.implicit:n.tag!==null&&(c=n.tag),c===null&&!n.any){let u=e.save();try{n.choice===null?this._decodeGeneric(n.tag,e,t):this._decodeChoice(e,t),s=!0}catch{s=!1}e.restore(u)}else if(s=this._peekTag(e,c,n.any),e.isError(s))return s}let a;if(n.obj&&s&&(a=e.enterObject()),s){if(n.explicit!==null){let u=this._decodeTag(e,n.explicit);if(e.isError(u))return u;e=u}let c=e.offset;if(n.use===null&&n.choice===null){let u;n.any&&(u=e.save());let p=this._decodeTag(e,n.implicit!==null?n.implicit:n.tag,n.any);if(e.isError(p))return p;n.any?i=e.raw(u):e=p}if(t&&t.track&&n.tag!==null&&t.track(e.path(),c,e.length,"tagged"),t&&t.track&&n.tag!==null&&t.track(e.path(),e.offset,e.length,"content"),n.any||(n.choice===null?i=this._decodeGeneric(n.tag,e,t):i=this._decodeChoice(e,t)),e.isError(i))return i;if(!n.any&&n.choice===null&&n.children!==null&&n.children.forEach(function(p){p._decode(e,t)}),n.contains&&(n.tag==="octstr"||n.tag==="bitstr")){let u=new uj(i);i=this._getUse(n.contains,e._reporterState.obj)._decode(u,t)}}return n.obj&&s&&(i=e.leaveObject(a)),n.key!==null&&(i!==null||s===!0)?e.leaveKey(o,n.key,i):o!==null&&e.exitKey(o),i};fe.prototype._decodeGeneric=function(e,t,n){let i=this._baseState;return e==="seq"||e==="set"?null:e==="seqof"||e==="setof"?this._decodeList(t,e,i.args[0],n):/str$/.test(e)?this._decodeStr(t,e,n):e==="objid"&&i.args?this._decodeObjid(t,i.args[0],i.args[1],n):e==="objid"?this._decodeObjid(t,null,null,n):e==="gentime"||e==="utctime"?this._decodeTime(t,e,n):e==="null_"?this._decodeNull(t,n):e==="bool"?this._decodeBool(t,n):e==="objDesc"?this._decodeStr(t,e,n):e==="int"||e==="enum"?this._decodeInt(t,i.args&&i.args[0],n):i.use!==null?this._getUse(i.use,t._reporterState.obj)._decode(t,n):t.error("unknown tag: "+e)};fe.prototype._getUse=function(e,t){let n=this._baseState;return n.useDecoder=this._use(e,t),Pt(n.useDecoder._baseState.parent===null),n.useDecoder=n.useDecoder._baseState.children[0],n.implicit!==n.useDecoder._baseState.implicit&&(n.useDecoder=n.useDecoder.clone(),n.useDecoder._baseState.implicit=n.implicit),n.useDecoder};fe.prototype._decodeChoice=function(e,t){let n=this._baseState,i=null,s=!1;return Object.keys(n.choice).some(function(o){let a=e.save(),c=n.choice[o];try{let u=c._decode(e,t);if(e.isError(u))return!1;i={type:o,value:u},s=!0}catch{return e.restore(a),!1}return!0},this),s?i:e.error("Choice not matched")};fe.prototype._createEncoderBuffer=function(e){return new lj(e,this.reporter)};fe.prototype._encode=function(e,t,n){let i=this._baseState;if(i.default!==null&&i.default===e)return;let s=this._encodeValue(e,t,n);if(s!==void 0&&!this._skipDefault(s,t,n))return s};fe.prototype._encodeValue=function(e,t,n){let i=this._baseState;if(i.parent===null)return i.children[0]._encode(e,t||new cj);let s=null;if(this.reporter=t,i.optional&&e===void 0)if(i.default!==null)e=i.default;else return;let o=null,a=!1;if(i.any)s=this._createEncoderBuffer(e);else if(i.choice)s=this._encodeChoice(e,t);else if(i.contains)o=this._getUse(i.contains,n)._encode(e,t),a=!0;else if(i.children)o=i.children.map(function(c){if(c._baseState.tag==="null_")return c._encode(null,t,e);if(c._baseState.key===null)return t.error("Child should have a key");let u=t.enterKey(c._baseState.key);if(typeof e!="object")return t.error("Child expected, but input is not object");let p=c._encode(e[c._baseState.key],t,e);return t.leaveKey(u),p},this).filter(function(c){return c}),o=this._createEncoderBuffer(o);else if(i.tag==="seqof"||i.tag==="setof"){if(!(i.args&&i.args.length===1))return t.error("Too many args for : "+i.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");let c=this.clone();c._baseState.implicit=null,o=this._createEncoderBuffer(e.map(function(u){let p=this._baseState;return this._getUse(p.args[0],e)._encode(u,t)},c))}else i.use!==null?s=this._getUse(i.use,n)._encode(e,t):(o=this._encodePrimitive(i.tag,e),a=!0);if(!i.any&&i.choice===null){let c=i.implicit!==null?i.implicit:i.tag,u=i.implicit===null?"universal":"context";c===null?i.use===null&&t.error("Tag could be omitted only for .use()"):i.use===null&&(s=this._encodeComposite(c,a,u,o))}return i.explicit!==null&&(s=this._encodeComposite(i.explicit,!1,"context",s)),s};fe.prototype._encodeChoice=function(e,t){let n=this._baseState,i=n.choice[e.type];return i||Pt(!1,e.type+" not found in "+JSON.stringify(Object.keys(n.choice))),i._encode(e.value,t)};fe.prototype._encodePrimitive=function(e,t){let n=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if(e==="objid"&&n.args)return this._encodeObjid(t,n.reverseArgs[0],n.args[1]);if(e==="objid")return this._encodeObjid(t,null,null);if(e==="gentime"||e==="utctime")return this._encodeTime(t,e);if(e==="null_")return this._encodeNull();if(e==="int"||e==="enum")return this._encodeInt(t,n.args&&n.reverseArgs[0]);if(e==="bool")return this._encodeBool(t);if(e==="objDesc")return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)};fe.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)};fe.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(e)}});var Yl=O(vi=>{"use strict";function vE(r){let e={};return Object.keys(r).forEach(function(t){(t|0)==t&&(t=t|0);let n=r[t];e[n]=t}),e}vi.tagClass={0:"universal",1:"application",2:"context",3:"private"};vi.tagClassByName=vE(vi.tagClass);vi.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"};vi.tagByName=vE(vi.tag)});var Gh=O((OG,_E)=>{"use strict";var hj=Gn(),yn=Gl().Buffer,xE=Kl(),Wh=Yl();function yE(r){this.enc="der",this.name=r.name,this.entity=r,this.tree=new Rr,this.tree._init(r.body)}_E.exports=yE;yE.prototype.encode=function(e,t){return this.tree._encode(e,t).join()};function Rr(r){xE.call(this,"der",r)}hj(Rr,xE);Rr.prototype._encodeComposite=function(e,t,n,i){let s=mj(e,t,n,this.reporter);if(i.length<128){let c=yn.alloc(2);return c[0]=s,c[1]=i.length,this._createEncoderBuffer([c,i])}let o=1;for(let c=i.length;c>=256;c>>=8)o++;let a=yn.alloc(2+o);a[0]=s,a[1]=128|o;for(let c=1+o,u=i.length;u>0;c--,u>>=8)a[c]=u&255;return this._createEncoderBuffer([a,i])};Rr.prototype._encodeStr=function(e,t){if(t==="bitstr")return this._createEncoderBuffer([e.unused|0,e.data]);if(t==="bmpstr"){let n=yn.alloc(e.length*2);for(let i=0;i<e.length;i++)n.writeUInt16BE(e.charCodeAt(i),i*2);return this._createEncoderBuffer(n)}else return t==="numstr"?this._isNumstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: numstr supports only digits and space"):t==="printstr"?this._isPrintstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark"):/str$/.test(t)?this._createEncoderBuffer(e):t==="objDesc"?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: "+t+" unsupported")};Rr.prototype._encodeObjid=function(e,t,n){if(typeof e=="string"){if(!t)return this.reporter.error("string objid given, but no values map found");if(!t.hasOwnProperty(e))return this.reporter.error("objid not found in values map");e=t[e].split(/[\s.]+/g);for(let a=0;a<e.length;a++)e[a]|=0}else if(Array.isArray(e)){e=e.slice();for(let a=0;a<e.length;a++)e[a]|=0}if(!Array.isArray(e))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(e));if(!n){if(e[1]>=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,e[0]*40+e[1])}let i=0;for(let a=0;a<e.length;a++){let c=e[a];for(i++;c>=128;c>>=7)i++}let s=yn.alloc(i),o=s.length-1;for(let a=e.length-1;a>=0;a--){let c=e[a];for(s[o--]=c&127;(c>>=7)>0;)s[o--]=128|c&127}return this._createEncoderBuffer(s)};function mr(r){return r<10?"0"+r:r}Rr.prototype._encodeTime=function(e,t){let n,i=new Date(e);return t==="gentime"?n=[mr(i.getUTCFullYear()),mr(i.getUTCMonth()+1),mr(i.getUTCDate()),mr(i.getUTCHours()),mr(i.getUTCMinutes()),mr(i.getUTCSeconds()),"Z"].join(""):t==="utctime"?n=[mr(i.getUTCFullYear()%100),mr(i.getUTCMonth()+1),mr(i.getUTCDate()),mr(i.getUTCHours()),mr(i.getUTCMinutes()),mr(i.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(n,"octstr")};Rr.prototype._encodeNull=function(){return this._createEncoderBuffer("")};Rr.prototype._encodeInt=function(e,t){if(typeof e=="string"){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if(typeof e!="number"&&!yn.isBuffer(e)){let s=e.toArray();!e.sign&&s[0]&128&&s.unshift(0),e=yn.from(s)}if(yn.isBuffer(e)){let s=e.length;e.length===0&&s++;let o=yn.alloc(s);return e.copy(o),e.length===0&&(o[0]=0),this._createEncoderBuffer(o)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);let n=1;for(let s=e;s>=256;s>>=8)n++;let i=new Array(n);for(let s=i.length-1;s>=0;s--)i[s]=e&255,e>>=8;return i[0]&128&&i.unshift(0),this._createEncoderBuffer(yn.from(i))};Rr.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)};Rr.prototype._use=function(e,t){return typeof e=="function"&&(e=e(t)),e._getEncoder("der").tree};Rr.prototype._skipDefault=function(e,t,n){let i=this._baseState,s;if(i.default===null)return!1;let o=e.join();if(i.defaultBuffer===void 0&&(i.defaultBuffer=this._encodeValue(i.default,t,n).join()),o.length!==i.defaultBuffer.length)return!1;for(s=0;s<o.length;s++)if(o[s]!==i.defaultBuffer[s])return!1;return!0};function mj(r,e,t,n){let i;if(r==="seqof"?r="seq":r==="setof"&&(r="set"),Wh.tagByName.hasOwnProperty(r))i=Wh.tagByName[r];else if(typeof r=="number"&&(r|0)===r)i=r;else return n.error("Unknown tag: "+r);return i>=31?n.error("Multi-octet tag encoding unsupported"):(e||(i|=32),i|=Wh.tagClassByName[t||"universal"]<<6,i)}});var wE=O((PG,bE)=>{"use strict";var gj=Gn(),zh=Gh();function Vh(r){zh.call(this,r),this.enc="pem"}gj(Vh,zh);bE.exports=Vh;Vh.prototype.encode=function(e,t){let i=zh.prototype.encode.call(this,e).toString("base64"),s=["-----BEGIN "+t.label+"-----"];for(let o=0;o<i.length;o+=64)s.push(i.slice(o,o+64));return s.push("-----END "+t.label+"-----"),s.join(`
|
|
91
|
+
`),Ml.add(e),r.on("close",()=>Ml.delete(e))}function nS(r,e){ee(e,{...dn,...Ar,desktopEnabled:jt,remoteAvailable:Eh})}async function iS(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Gt(),Ii)),n=await t(r,e);n&&(hn(n),ee(e))}function sS(r,e){ee(e),hn({step:Xn.PREPARING,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null}),$n("restart-tunnel")}function oS(r,e){ee(e),hn({step:Xn.PREPARING,stepDesc:""}),$n("start-tunnel")}function aS(r,e){ee(e),hn({step:Xn.STOPPED,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null}),$n("stop-tunnel")}function cS(r,e){ee(e),hn({step:Xn.STOPPED,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null}),$n("shutdown")}function lS(r,e){ee(e),$n("update")}function uS(r,e){ee(e,{connections:[...hi.values()]})}function pS(r,e){let t=new URL(r.url,"http://localhost"),n=parseInt(t.searchParams.get("lines")||Rp,10);ee(e,{logs:Hv(Number.isFinite(n)?n:Rp)})}async function fS(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Gt(),Ii)),n=await t(r,e);if(!n)return;let i=!!n.enabled;if(i&&(!Ar.screenRecording||!Ar.accessibility)){ee(e,{ok:!1,enabled:jt,reason:"permissions_required"});return}let s=Es();jt=i,Sh(),St("permissions",{...Ar,desktopEnabled:jt}),Es()!==s&&Th?.(),ee(e,{ok:!0,enabled:jt})}function dS(r,e){ee(e,Ar)}async function hS(r,e){let t=await hh();ee(e,{enabled:t})}async function mS(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Gt(),Ii)),n=await t(r,e);if(!n)return;let i=await Dw(!!n.enabled),s=await hh();St("autostart",{enabled:s}),ee(e,{ok:i,enabled:s})}async function gS(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Gt(),Ii)),n=await t(r,e);if(!n)return;let{type:i}=n;if(process.platform==="darwin"){Ow(i);let s=Date.now(),o=setInterval(async()=>{((await Nl())[i]||Date.now()-s>Nv)&&clearInterval(o)},Iv)}ee(e)}var Hn,qw,wh,dn,jt,Eh,Ar,Ml,hi,Il,Th,Un=Ce(()=>{vt();Li();vt();ys();Pw();mh();Gt();cl();vt();Hn=require("fs"),qw=require("path");vt();gh();wh=(0,qw.join)(oe.STATE,"ui-state.json");dn={step:Xn.STOPPED,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null,permanentKey:"",qrUrl:"",latency:null,uptime:null,healthCheck:{running:!1,timeoutMs:0,startedAt:null,logs:[]},tunnelHealth:{status:"unknown",checkedAt:null}},jt=!1,Eh=!1,Ar={screenRecording:!1,accessibility:!1},Ml=new Set,hi=new Map;$v(Te);Il=null;Th=null});var Ll,vS=Ce(()=>{bt();Un();Ll=class{constructor(){this.cfg=Z.logging,this.samples=[],this.lastLogTime=Date.now()}now(){return this.cfg.metrics?performance.now():0}record({capture:e,checksum:t,encode:n,total:i,changedTiles:s,totalTiles:o,tileBytes:a,rawBytes:c}){this.cfg.metrics&&(this.samples.push({capture:e,checksum:t,encode:n,total:i,changedTiles:s,totalTiles:o,tileBytes:a,rawBytes:c}),this.samples.length>=this.cfg.metricsEveryFrames&&this._flush())}_flush(){let e=this.samples.length,t=N=>(this.samples.reduce(($,W)=>$+W[N],0)/e).toFixed(1),n=(Date.now()-this.lastLogTime)/1e3,i=(e/n).toFixed(1),s=[],o=0;for(let N of this.samples){for(let $ of N.tileBytes)s.push($);o+=N.tileBytes.reduce(($,W)=>$+W,0)}let a=(o/e/1024).toFixed(1),c=s.length?(s.reduce((N,$)=>N+$,0)/s.length/1024).toFixed(2):"0",u=s.length?(Math.min(...s)/1024).toFixed(2):"0",p=s.length?(Math.max(...s)/1024).toFixed(2):"0",f=this.samples.reduce((N,$)=>N+$.rawBytes,0)/e,m=o/e,y=m>0?(f/m).toFixed(0):"0",_=(this.samples.reduce((N,$)=>N+$.changedTiles,0)/e).toFixed(0),S=this.samples[0]?.totalTiles||0,A=S?(_/S*100).toFixed(1):"0",P=Z.pipeline,L=`[Metrics] ${P.captureLib}+${P.encoder} tile=${P.tileSize} q${P.jpegQuality} scale=${P.outputScale} | fps=${i} | capture=${t("capture")}ms enc=${t("encode")}ms total=${t("total")}ms | tiles=${_}/${S} (${A}%) | data=${a}KB/frame | tileAvg=${c}KB (min ${u}, max ${p}) | compress=${y}x`;Te(L),console.log(L),this.samples=[],this.lastLogTime=Date.now()}}});var _S={};Xr(_S,{TileManager:()=>Ch});var Ts,Bl,xS,Dl,yS,XB,JB,Ch,bS=Ce(()=>{Ts=X(require("fs"),1),Bl=X(require("path"),1),xS=X(require("sharp"),1),Dl=require("child_process"),yS=require("url");bt();Sw();Tw();vS();Kd();XB=(0,yS.fileURLToPath)(__importMetaUrl),JB=Bl.default.dirname(XB),Ch=class{constructor(e){this.robot=e,this.metrics=new Ll,this.tileSize=Z.pipeline.tileSize,this.lastTileChecksums=new Map,this.screenWidth=0,this.screenHeight=0,this.tilesPerRow=0,this.tilesPerColumn=0,this.totalTiles=0,this.frameCount=0,this.tempDir=Bl.default.join(JB,"../../temp"),this.changeThreshold=1,this.scaledWidth=0,this.scaledHeight=0,this.isProcessing=!1,this.sharedScreenCache=null,this.lastCaptureTime=0,this.CACHE_TTL=100,this.dpiScale=1,this.captureWidth=0,this.captureHeight=0,this.scaleFactor=Z.pipeline.outputScale||1,this.compressionQuality=Z.pipeline.jpegQuality,this.activeTileSet=null,this.focusStats={frames:0,scanned:0,changed:0,bytes:0},Ts.default.existsSync(this.tempDir)||Ts.default.mkdirSync(this.tempDir,{recursive:!0}),bw(e),this.initializeScreenDimensions()}initializeScreenDimensions(){try{let{width:e,height:t}=this.robot.getScreenSize();this.screenWidth=e,this.screenHeight=t,this.detectDpiScale(),this.scaledWidth=this.captureWidth,this.scaledHeight=this.captureHeight,this.tilesPerRow=Math.ceil(this.scaledWidth/this.tileSize),this.tilesPerColumn=Math.ceil(this.scaledHeight/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn;let n=100;if(this.totalTiles>n){let i=Math.ceil(Math.sqrt(this.scaledWidth*this.scaledHeight/n));this.tileSize=Math.max(i,120),this.tilesPerRow=Math.ceil(this.scaledWidth/this.tileSize),this.tilesPerColumn=Math.ceil(this.scaledHeight/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn}}catch(e){ve.error("Screen dimensions error:",e),this.screenWidth=1920,this.screenHeight=1080,this.dpiScale=1,this.captureWidth=1920,this.captureHeight=1080,this.scaledWidth=1728,this.scaledHeight=972,this.tileSize=120,this.tilesPerRow=Math.ceil(this.scaledWidth/this.tileSize),this.tilesPerColumn=Math.ceil(this.scaledHeight/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn}}detectDpiScale(){if(process.platform==="darwin"){let e=this.robot.screen.capture(0,0,this.screenWidth,this.screenHeight),n=e.byteWidth/e.bytesPerPixel/this.screenWidth;n>=1.9&&n<=2.1?this.dpiScale=2:this.dpiScale=1}else process.platform==="win32"?this.dpiScale=this._detectDpiScaleWin32():this.dpiScale=1;this.captureWidth=Math.floor(this.screenWidth*this.dpiScale),this.captureHeight=Math.floor(this.screenHeight*this.dpiScale)}_detectDpiScaleWin32(){ve.dpi(`\u{1F50D} [DPI Detection] screenWidth from robot: ${this.screenWidth}x${this.screenHeight}`);try{let e=(0,Dl.execSync)(`powershell -NonInteractive -NoProfile -WindowStyle Hidden -command "try{Get-ItemPropertyValue 'HKCU:\\Control Panel\\Desktop\\WindowMetrics' -Name AppliedDPI}catch{0}"`,{encoding:"utf8",windowsHide:!0}).trim(),t=Number(e);if(ve.dpi(`\u{1F50D} [DPI Detection] Strategy 1 (Registry AppliedDPI): ${t} DPI`),t>=96){let n=t/96;return ve.dpi(`\u2705 [DPI Detection] Using registry scale: ${n}x (${t}/96)`),n}}catch(e){ve.dpi(`\u274C [DPI Detection] Strategy 1 failed: ${e.message}`)}try{let e=(0,Dl.execSync)('powershell -NonInteractive -NoProfile -WindowStyle Hidden -command "(Get-WmiObject -Class Win32_VideoController | Select-Object -First 1).CurrentHorizontalResolution"',{encoding:"utf8",windowsHide:!0}).trim(),t=Number(e);if(ve.dpi(`\u{1F50D} [DPI Detection] Strategy 2 (WMI): physical width = ${t}px`),t>0&&t>this.screenWidth){let n=t/this.screenWidth;return ve.dpi(`\u2705 [DPI Detection] Using WMI scale: ${n}x (${t}/${this.screenWidth})`),n}}catch(e){ve.dpi(`\u274C [DPI Detection] Strategy 2 failed: ${e.message}`)}try{let e=(0,Dl.execSync)(`powershell -NonInteractive -NoProfile -WindowStyle Hidden -command "Add-Type -TypeDefinition 'using System;using System.Runtime.InteropServices;public class Disp{[DllImport(\\"user32\\")]public static extern bool EnumDisplaySettings(string d,int m,ref DEVMODE dm);[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]public struct DEVMODE{[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)]public string dmDeviceName;public short dmSpecVersion,dmDriverVersion,dmSize,dmDriverExtra;public int dmFields;public int dmPositionX,dmPositionY,dmDisplayOrientation,dmDisplayFixedOutput;public short dmColor,dmDuplex,dmYResolution,dmTTOption,dmCollate;[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)]public string dmFormName;public short dmLogPixels;public int dmBitsPerPel,dmPelsWidth,dmPelsHeight,dmDisplayFlags,dmDisplayFrequency;}}'; $dm=New-Object Disp+DEVMODE; $dm.dmSize=[System.Runtime.InteropServices.Marshal]::SizeOf($dm); [Disp]::EnumDisplaySettings($null,-1,[ref]$dm) | Out-Null; Write-Output $dm.dmPelsWidth"`,{encoding:"utf8",windowsHide:!0}).trim(),t=Number(e);if(ve.dpi(`\u{1F50D} [DPI Detection] Strategy 3 (EnumDisplaySettings): physical width = ${t}px`),t>0&&t>this.screenWidth){let n=t/this.screenWidth;return ve.dpi(`\u2705 [DPI Detection] Using EnumDisplaySettings scale: ${n}x (${t}/${this.screenWidth})`),n}}catch(e){ve.dpi(`\u274C [DPI Detection] Strategy 3 failed: ${e.message}`)}return ve.dpi("\u26A0\uFE0F [DPI Detection] All strategies failed, fallback to 1x"),1}async captureFullScreen(){let e=await ww();return{buffer:e.buffer,width:e.width,height:e.height,channels:e.channels}}async getSharedScreenCapture(){let e=Date.now();return this.sharedScreenCache&&e-this.lastCaptureTime<this.CACHE_TTL?this.sharedScreenCache:(this.sharedScreenCache=await this.captureFullScreen(),this.lastCaptureTime=e,this.sharedScreenCache)}clearScreenCache(){}async detectChangedTiles(){return(await this.detectChangedTilesWithHashes()).tiles}async detectChangedTilesWithHashes(){if(this.isProcessing)return{tiles:[],currentHashes:Array.from(this.lastTileChecksums.values())};this.isProcessing=!0;let e=this.metrics.now(),t=e,n=e;try{let i=await this.getSharedScreenCapture();t=this.metrics.now();let s=[],o=[],a=new Map;this.frameCount++;let c=this.activeTileSet;for(let f=0;f<this.totalTiles;f++){if(c&&!c.has(f))continue;let m=this.calculateTileChecksumDirect(i,f);a.set(f,m)}n=this.metrics.now();let u=Array.from(a.values());if(this.lastTileChecksums.size===0){let f=[];for(let y=0;y<this.totalTiles;y++)c&&!c.has(y)||(this.lastTileChecksums.set(y,a.get(y)),f.push(this.processTileAsync(i,y)));let m=await Promise.all(f);return s.push(...m),this._recordFrame(e,t,n,s,i),{tiles:s,currentHashes:u}}for(let f=0;f<this.totalTiles;f++){if(c&&!c.has(f))continue;let m=a.get(f),y=this.lastTileChecksums.get(f);m!==y&&(o.push(f),this.lastTileChecksums.set(f,m))}if(o.length/this.totalTiles>this.changeThreshold){let f=[];for(let y=0;y<this.totalTiles;y++)c&&!c.has(y)||f.push(this.processTileAsync(i,y));let m=await Promise.all(f);s.push(...m.map(y=>({...y,fullRefresh:!0})))}else if(o.length>0){let f=o.map(y=>this.processTileAsync(i,y)),m=await Promise.all(f);s.push(...m)}return this._recordFrame(e,t,n,s,i),{tiles:s,currentHashes:u}}finally{this.isProcessing=!1}}async processTileAsync(e,t,n=null){let i=n||this.extractTile(e,t),s=await this.compressTileImage(i.buffer,i.width,i.height),{row:o,col:a}=this.getTilePosition(t);return{type:"tile-update",tileIndex:t,x:a*this.tileSize,y:o*this.tileSize,width:i.width,height:i.height,imageBuffer:s,hash:this.lastTileChecksums.get(t)??0,timestamp:Date.now(),frameCount:this.frameCount}}calculateTileChecksumDirect(e,t){let{row:n,col:i}=this.getTilePosition(t),s=i*this.tileSize,o=n*this.tileSize,a=Math.min(s+this.tileSize,e.width),c=Math.min(o+this.tileSize,e.height),u=a-s,p=c-o,f=e.channels,m=e.width*f,y=0,_=16;for(let S=0;S<p;S+=4){let A=(S>>2&1)*8,P=(o+S)*m+s*f;for(let L=A;L<u;L+=_){let N=P+L*f;y+=e.buffer[N],y^=e.buffer[N+1],y+=e.buffer[N+2]<<1,y^=e.buffer[N+3]<<2}}return y>>>0}setFocusRect(e){if(!e){this.activeTileSet=null;return}let t=Z.focus.paddingTiles,n=Math.max(0,Math.floor(e.x/this.tileSize)-t),i=Math.max(0,Math.floor(e.y/this.tileSize)-t),s=Math.min(this.tilesPerRow-1,Math.floor((e.x+e.w)/this.tileSize)+t),o=Math.min(this.tilesPerColumn-1,Math.floor((e.y+e.h)/this.tileSize)+t),a=new Set;for(let u=i;u<=o;u++)for(let p=n;p<=s;p++)a.add(u*this.tilesPerRow+p);let c=this.activeTileSet;if(c)for(let u of a)c.has(u)||this.lastTileChecksums.delete(u);this.activeTileSet=a}getTilePosition(e){return{row:Math.floor(e/this.tilesPerRow),col:e%this.tilesPerRow}}extractTile(e,t){let{row:n,col:i}=this.getTilePosition(t),s=i*this.tileSize,o=n*this.tileSize,a=Math.min(s+this.tileSize,e.width),c=Math.min(o+this.tileSize,e.height),u=a-s,p=c-o,f=e.channels,m=u*f,y=Buffer.alloc(u*p*f);for(let _=0;_<p;_++){let S=((o+_)*e.width+s)*f,A=_*m;e.buffer.copy(y,A,S,S+m)}return{buffer:y,width:u,height:p,channels:f,tileIndex:t,x:s,y:o}}async compressTileImage(e,t,n){let i=this.scaleFactor;if(i&&i>0&&i<1){let s=Math.max(1,Math.floor(t*i)),o=Math.max(1,Math.floor(n*i)),{inputFormat:a}=Z.pipeline,c=e,u=4;a==="bgra"&&(c=Buffer.from(e),ah(c));let p=await(0,xS.default)(c,{raw:{width:t,height:n,channels:u}}).resize(s,o,{kernel:"lanczos3",fastShrinkOnLoad:!1}).raw().toBuffer();return ch(p,s,o,4,this.compressionQuality,"rgba")}return ch(e,t,n,4,this.compressionQuality)}pickProfile({zoom:e=1,viewerWidth:t=0,dpr:n=1}={}){let i=Z.pipeline.adaptiveTiers||[];if(!i.length)return null;let s=this.captureWidth||this.screenWidth||1,o=t>0?t:s,a=e>0?e:1,c=n>0?n:1,u=o*a*c/s,p=Z.pipeline.tierHysteresis||0,f=this._currentTier;for(let y of i){let _=f&&y===f?y.minEffective-p:y.minEffective;if(u>=_)return this._currentTier=y,y}let m=i[i.length-1];return this._currentTier=m,m}setProfile(e){if(!e)return;let t=e.outputScale??this.scaleFactor,n=e.jpegQuality??this.compressionQuality;t===this.scaleFactor&&n===this.compressionQuality||(this.scaleFactor=t,this.compressionQuality=n,this.lastTileChecksums.clear())}_recordFrame(e,t,n,i,s){if(this._recordFocusFrame(i),!this.metrics.cfg.metrics)return;let o=this.metrics.now(),a=i.map(u=>u.imageBuffer?.length||0),c=s?s.width*s.height*s.channels:0;this.metrics.record({capture:t-e,checksum:n-t,encode:o-n,total:o-e,changedTiles:i.length,totalTiles:this.totalTiles,tileBytes:a,rawBytes:c})}_recordFocusFrame(e){let t=this.focusStats;t.frames++,t.scanned+=this.activeTileSet?this.activeTileSet.size:this.totalTiles,t.changed+=e.length;for(let c of e)t.bytes+=c.imageBuffer?.length||0;if(t.frames<Z.logging.focusEveryFrames)return;let n=(t.scanned/t.frames).toFixed(0),i=(t.changed/t.frames).toFixed(1),s=(t.bytes/t.frames/1024).toFixed(1),o=this.totalTiles?((1-n/this.totalTiles)*100).toFixed(0):0,a=this.activeTileSet?"focus":"full";ve.focus(`\u{1F3AF} [Focus/${a}] ${t.frames}f | scan ${n}/${this.totalTiles} tiles (saved ${o}%) | changed ${i}/f | data ${s}KB/f`),this.focusStats={frames:0,scanned:0,changed:0,bytes:0}}async getScreenDimensions(){try{let e=await this.captureFullScreen();this.scaledWidth=e.width,this.scaledHeight=e.height,this.tilesPerRow=Math.ceil(e.width/this.tileSize),this.tilesPerColumn=Math.ceil(e.height/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn}catch(e){ve.error("Error getting dimensions:",e)}return{width:this.scaledWidth,height:this.scaledHeight,tileWidth:this.tileSize,tileHeight:this.tileSize,tileCount:this.totalTiles,scaleFactor:this.scaleFactor,originalWidth:this.screenWidth,originalHeight:this.screenHeight}}async compareClientTileHashes(e){if(this.isProcessing)return{tiles:[],currentHashes:[],changedIndices:[]};this.isProcessing=!0;try{let t=await this.getSharedScreenCapture(),n=[],i=[];this.frameCount++;let s=this.activeTileSet,o=new Map;for(let c=0;c<this.totalTiles;c++){if(s&&!s.has(c))continue;let u=this.calculateTileChecksumDirect(t,c);o.set(c,u),this.lastTileChecksums.set(c,u)}if(!e||e.length===0){let c=[];for(let p=0;p<this.totalTiles;p++)s&&!s.has(p)||c.push(this.processTileAsync(t,p));let u=await Promise.all(c);return n.push(...u),{tiles:n,currentHashes:Array.from(o.values())}}for(let c=0;c<this.totalTiles;c++)s&&!s.has(c)||e[c]!==o.get(c)&&i.push(c);if(i.length/this.totalTiles>this.changeThreshold){let c=[];for(let p=0;p<this.totalTiles;p++)s&&!s.has(p)||c.push(this.processTileAsync(t,p));let u=await Promise.all(c);n.push(...u.map(p=>({...p,fullRefresh:!0})))}else if(i.length>0){let c=i.map(p=>this.processTileAsync(t,p)),u=await Promise.all(c);n.push(...u)}return this._recordFocusFrame(n),{tiles:n,currentHashes:Array.from(o.values()),changedIndices:i}}finally{this.isProcessing=!1}}clearMemory(){this.sharedScreenCache=null,this.lastCaptureTime=0,this.lastTileChecksums.clear()}reset(){this.lastTileChecksums.clear(),this.frameCount=0}cleanup(){try{Ts.default.existsSync(this.tempDir)&&Ts.default.readdirSync(this.tempDir).forEach(t=>Ts.default.unlinkSync(Bl.default.join(this.tempDir,t)))}catch(e){ve.warn(`Cleanup error: ${e.message}`)}}}});var wS={};Xr(wS,{ResourceManager:()=>Ah});var Ah,SS=Ce(()=>{bt();Ah=class{constructor(){this.activeClients=new Map,this.activeTimers=new Map,this.chunkTimers=new Map,this.memoryCheckInterval=null}startResourceMonitoring(){this.memoryCheckInterval=setInterval(()=>{let e=process.memoryUsage(),t=Math.round(e.heapUsed/1024/1024);t>Z.resourceManagement.memoryWarningThreshold&&(console.warn(`\u26A0\uFE0F High memory: ${t}MB`),this.cleanupInactiveClients())},Z.resourceManagement.memoryCheckInterval)}stopResourceMonitoring(){this.memoryCheckInterval&&(clearInterval(this.memoryCheckInterval),this.memoryCheckInterval=null)}addClient(e,t){this.activeClients.set(e,{...t,lastActivity:Date.now()})}getClient(e){return this.activeClients.get(e)}updateClientActivity(e){let t=this.activeClients.get(e);t&&(t.lastActivity=Date.now())}cleanupInactiveClients(){let e=Date.now(),t=Z.resourceManagement.inactiveTimeout;for(let[n,i]of this.activeClients.entries())e-i.lastActivity>t&&(console.log(`\u{1F9F9} Cleaning inactive client: ${n}`),this.cleanupClientResources(n,i),this.activeClients.delete(n))}cleanupClientResources(e,t){try{t.isStreaming=!1,t?.streamingTimeout&&(clearTimeout(t.streamingTimeout),t.streamingTimeout=null),t?.screenInterval&&(clearInterval(t.screenInterval),t.screenInterval=null);let n=this.activeTimers.get(e);n&&(n.forEach(s=>clearTimeout(s)),this.activeTimers.delete(e));let i=this.chunkTimers.get(e);i&&(i.forEach(s=>clearTimeout(s)),this.chunkTimers.delete(e)),t?.tileManager&&(t.tileManager.clearMemory(),t.tileManager.cleanup(),t.tileManager.reset())}catch(n){console.error(`Error cleaning up ${e}:`,n.message)}}getStreamingConfig(){return Z.streaming}getWebRTCConfig(){return Z.webrtc}removeClient(e){let t=this.activeClients.get(e);t&&(this.cleanupClientResources(e,t),this.activeClients.delete(e))}getChunkTimers(e){return this.chunkTimers.has(e)||this.chunkTimers.set(e,new Set),this.chunkTimers.get(e)}cleanupAll(){this.stopResourceMonitoring();for(let[e,t]of this.activeClients.entries())this.cleanupClientResources(e,t);this.activeClients.clear(),this.activeTimers.clear(),this.chunkTimers.clear()}}});var ES={};Xr(ES,{ScreenUpdateHelper:()=>Rh});var Rh,TS=Ce(()=>{bt();Rh=class{constructor(e){this.resourceManager=e}async sendTilesInChunks(e,t,n,i=!1){if(!t||t.length===0)return;let s=Z.streaming.chunkSize,o=[];for(let c=0;c<t.length;c+=s)o.push(t.slice(c,c+s));let a=this.resourceManager.getChunkTimers(e.id);for(let c=0;c<o.length;c++){let u=o[c],p=c===o.length-1,f=setTimeout(()=>{a.delete(f),e.connected&&e.emit("tiles-data",{tiles:u,timestamp:n,forceRefresh:!1,userAction:i,chunkInfo:{chunkIndex:c,totalChunks:o.length,isLastChunk:p}})},c*Z.streaming.chunkDelay);a.add(f)}}}});var CS={};Xr(CS,{MouseHandler:()=>kh});var kh,AS=Ce(()=>{bt();kh=class{constructor(e,t){this.robot=e,this.resourceManager=t,this.lastMouseMove=0}setupMouseHandlers(e,t){let n=this.robot;e.on("mouse-move",t(i=>{let s=Date.now();if(!(s-this.lastMouseMove<Z.throttling.mouseThrottle)){this.lastMouseMove=s;try{let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),u=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(u,p),this.resourceManager.updateClientActivity(e.id)}catch(o){console.error("Mouse move error:",o.message)}}})),e.on("mouse-click",t(async i=>{try{let s=this.resourceManager.getClient(e.id);if(!s)return;let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),u=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(u,p),n.mouseClick(i.button||"left",i.double||!1),s.idleFrameCount=0,this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Mouse click error:",s.message)}})),e.on("mouse-press",t(async i=>{try{if(!this.resourceManager.getClient(e.id))return;let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),u=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(u,p),n.mouseToggle("down",i.button||"left"),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Mouse press error:",s.message)}})),e.on("mouse-release",t(async i=>{try{if(!this.resourceManager.getClient(e.id))return;let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),u=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(u,p),n.mouseToggle("up",i.button||"left"),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Mouse release error:",s.message)}})),e.on("scroll",t(async i=>{try{let{direction:s,amount:o=60,horizontal:a=!1}=i,c=this.resourceManager.getClient(e.id);if(!c)return;let u=0,p=0;a||s==="left"||s==="right"?u=s==="right"?o:-o:p=s==="down"?-o:o,n.scrollMouse(u,p),c.idleFrameCount=0,this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Scroll error:",s.message)}})),e.on("mouse-drag-select",t(i=>{try{let{startX:s,startY:o,endX:a,endY:c}=i,u=n.getScreenSize(),p=Math.round(s/100*u.width),f=Math.round(o/100*u.height),m=Math.round(a/100*u.width),y=Math.round(c/100*u.height),_=Math.max(0,Math.min(u.width-1,p)),S=Math.max(0,Math.min(u.height-1,f)),A=Math.max(0,Math.min(u.width-1,m)),P=Math.max(0,Math.min(u.height-1,y));n.moveMouse(_,S),n.mouseToggle("down","left"),n.dragMouse(A,P),n.mouseToggle("up","left"),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Drag selection error:",s.message)}}))}}});var kS={};Xr(kS,{KeyboardHandler:()=>Oh});function QB(r){let e;r.type==="missionControl"?e='tell application "System Events" to key code 160':e=`tell application "System Events" to key code ${r.keyCode} using ${r.mods}`,(0,RS.execFile)("osascript",["-e",e],t=>{t&&console.error("osascript error:",t.message)})}var RS,Oh,OS=Ce(()=>{RS=require("child_process");bt();Oh=class{constructor(e,t){this.robot=e,this.resourceManager=t,this.lastKeyPress=0,this.lastTypeText=0}setupKeyboardHandlers(e,t){let n=this.robot;e.on("key-press",t(i=>{let s=Date.now();if(!(s-this.lastKeyPress<Z.throttling.keyThrottle)){this.lastKeyPress=s;try{if(!i.key||typeof i.key!="string")return;let o=this.resourceManager.getClient(e.id),a=i.key,c=i.modifier||[];if(a.length===1)if(c.filter(p=>p!=="shift").length>0){n.keyTap(a.toLowerCase(),c);for(let p of c)n.keyToggle(p,"up")}else n.typeString(a);else{let p={return:"enter"}[a.toLowerCase()]??a.toLowerCase();n.keyTap(p,c)}o&&(o.idleFrameCount=0),this.resourceManager.updateClientActivity(e.id)}catch(o){console.error("Key press error:",o.message)}}})),e.on("desktop-switch",t(i=>{try{let s=i?.direction,o=Z.desktopSwitch[process.platform]?.[s];if(!o)return;process.platform==="darwin"?QB(o):n.keyTap(o[0],o[1]);let a=this.resourceManager.getClient(e.id);a&&(a.idleFrameCount=0),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Desktop switch error:",s.message)}})),e.on("type-text",t(i=>{let s=Date.now();if(!(s-this.lastTypeText<Z.throttling.typeTextThrottle)){this.lastTypeText=s;try{if(!i.text||typeof i.text!="string")return;let o=i.text;o.length>Z.throttling.maxTextLength&&(o=o.substring(0,Z.throttling.maxTextLength));let a=o.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),c=this.resourceManager.getClient(e.id);setTimeout(()=>{try{n.typeString(a),this.resourceManager.updateClientActivity(e.id),c&&(c.idleFrameCount=0,c.tileManager&&c.tileManager.clearScreenCache())}catch(u){console.error("Robot typeString error:",u.message)}},10)}catch(o){console.error("Type text error:",o.message)}}}))}}});var Fh=O((cE,jh)=>{(function(r,e){"use strict";function t(T,l){if(!T)throw new Error(l||"Assertion failed")}function n(T,l){T.super_=l;var h=function(){};h.prototype=l.prototype,T.prototype=new h,T.prototype.constructor=T}function i(T,l,h){if(i.isBN(T))return T;this.negative=0,this.words=null,this.length=0,this.red=null,T!==null&&((l==="le"||l==="be")&&(h=l,l=10),this._init(T||0,l||10,h||"be"))}typeof r=="object"?r.exports=i:e.BN=i,i.BN=i,i.wordSize=26;var s;try{typeof window<"u"&&typeof window.Buffer<"u"?s=window.Buffer:s=require("buffer").Buffer}catch{}i.isBN=function(l){return l instanceof i?!0:l!==null&&typeof l=="object"&&l.constructor.wordSize===i.wordSize&&Array.isArray(l.words)},i.max=function(l,h){return l.cmp(h)>0?l:h},i.min=function(l,h){return l.cmp(h)<0?l:h},i.prototype._init=function(l,h,x){if(typeof l=="number")return this._initNumber(l,h,x);if(typeof l=="object")return this._initArray(l,h,x);h==="hex"&&(h=16),t(h===(h|0)&&h>=2&&h<=36),l=l.toString().replace(/\s+/g,"");var w=0;l[0]==="-"&&(w++,this.negative=1),w<l.length&&(h===16?this._parseHex(l,w,x):(this._parseBase(l,h,w),x==="le"&&this._initArray(this.toArray(),h,x)))},i.prototype._initNumber=function(l,h,x){l<0&&(this.negative=1,l=-l),l<67108864?(this.words=[l&67108863],this.length=1):l<4503599627370496?(this.words=[l&67108863,l/67108864&67108863],this.length=2):(t(l<9007199254740992),this.words=[l&67108863,l/67108864&67108863,1],this.length=3),x==="le"&&this._initArray(this.toArray(),h,x)},i.prototype._initArray=function(l,h,x){if(t(typeof l.length=="number"),l.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(l.length/3),this.words=new Array(this.length);for(var w=0;w<this.length;w++)this.words[w]=0;var g,v,C=0;if(x==="be")for(w=l.length-1,g=0;w>=0;w-=3)v=l[w]|l[w-1]<<8|l[w-2]<<16,this.words[g]|=v<<C&67108863,this.words[g+1]=v>>>26-C&67108863,C+=24,C>=26&&(C-=26,g++);else if(x==="le")for(w=0,g=0;w<l.length;w+=3)v=l[w]|l[w+1]<<8|l[w+2]<<16,this.words[g]|=v<<C&67108863,this.words[g+1]=v>>>26-C&67108863,C+=24,C>=26&&(C-=26,g++);return this.strip()};function o(T,l){var h=T.charCodeAt(l);return h>=65&&h<=70?h-55:h>=97&&h<=102?h-87:h-48&15}function a(T,l,h){var x=o(T,h);return h-1>=l&&(x|=o(T,h-1)<<4),x}i.prototype._parseHex=function(l,h,x){this.length=Math.ceil((l.length-h)/6),this.words=new Array(this.length);for(var w=0;w<this.length;w++)this.words[w]=0;var g=0,v=0,C;if(x==="be")for(w=l.length-1;w>=h;w-=2)C=a(l,h,w)<<g,this.words[v]|=C&67108863,g>=18?(g-=18,v+=1,this.words[v]|=C>>>26):g+=8;else{var b=l.length-h;for(w=b%2===0?h+1:h;w<l.length;w+=2)C=a(l,h,w)<<g,this.words[v]|=C&67108863,g>=18?(g-=18,v+=1,this.words[v]|=C>>>26):g+=8}this.strip()};function c(T,l,h,x){for(var w=0,g=Math.min(T.length,h),v=l;v<g;v++){var C=T.charCodeAt(v)-48;w*=x,C>=49?w+=C-49+10:C>=17?w+=C-17+10:w+=C}return w}i.prototype._parseBase=function(l,h,x){this.words=[0],this.length=1;for(var w=0,g=1;g<=67108863;g*=h)w++;w--,g=g/h|0;for(var v=l.length-x,C=v%w,b=Math.min(v,v-C)+x,d=0,E=x;E<b;E+=w)d=c(l,E,E+w,h),this.imuln(g),this.words[0]+d<67108864?this.words[0]+=d:this._iaddn(d);if(C!==0){var U=1;for(d=c(l,E,l.length,h),E=0;E<C;E++)U*=h;this.imuln(U),this.words[0]+d<67108864?this.words[0]+=d:this._iaddn(d)}this.strip()},i.prototype.copy=function(l){l.words=new Array(this.length);for(var h=0;h<this.length;h++)l.words[h]=this.words[h];l.length=this.length,l.negative=this.negative,l.red=this.red},i.prototype.clone=function(){var l=new i(null);return this.copy(l),l},i.prototype._expand=function(l){for(;this.length<l;)this.words[this.length++]=0;return this},i.prototype.strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},i.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var u=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],p=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];i.prototype.toString=function(l,h){l=l||10,h=h|0||1;var x;if(l===16||l==="hex"){x="";for(var w=0,g=0,v=0;v<this.length;v++){var C=this.words[v],b=((C<<w|g)&16777215).toString(16);g=C>>>24-w&16777215,w+=2,w>=26&&(w-=26,v--),g!==0||v!==this.length-1?x=u[6-b.length]+b+x:x=b+x}for(g!==0&&(x=g.toString(16)+x);x.length%h!==0;)x="0"+x;return this.negative!==0&&(x="-"+x),x}if(l===(l|0)&&l>=2&&l<=36){var d=p[l],E=f[l];x="";var U=this.clone();for(U.negative=0;!U.isZero();){var I=U.modn(E).toString(l);U=U.idivn(E),U.isZero()?x=I+x:x=u[d-I.length]+I+x}for(this.isZero()&&(x="0"+x);x.length%h!==0;)x="0"+x;return this.negative!==0&&(x="-"+x),x}t(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var l=this.words[0];return this.length===2?l+=this.words[1]*67108864:this.length===3&&this.words[2]===1?l+=4503599627370496+this.words[1]*67108864:this.length>2&&t(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-l:l},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(l,h){return t(typeof s<"u"),this.toArrayLike(s,l,h)},i.prototype.toArray=function(l,h){return this.toArrayLike(Array,l,h)},i.prototype.toArrayLike=function(l,h,x){var w=this.byteLength(),g=x||Math.max(1,w);t(w<=g,"byte array longer than desired length"),t(g>0,"Requested array length <= 0"),this.strip();var v=h==="le",C=new l(g),b,d,E=this.clone();if(v){for(d=0;!E.isZero();d++)b=E.andln(255),E.iushrn(8),C[d]=b;for(;d<g;d++)C[d]=0}else{for(d=0;d<g-w;d++)C[d]=0;for(d=0;!E.isZero();d++)b=E.andln(255),E.iushrn(8),C[g-d-1]=b}return C},Math.clz32?i.prototype._countBits=function(l){return 32-Math.clz32(l)}:i.prototype._countBits=function(l){var h=l,x=0;return h>=4096&&(x+=13,h>>>=13),h>=64&&(x+=7,h>>>=7),h>=8&&(x+=4,h>>>=4),h>=2&&(x+=2,h>>>=2),x+h},i.prototype._zeroBits=function(l){if(l===0)return 26;var h=l,x=0;return(h&8191)===0&&(x+=13,h>>>=13),(h&127)===0&&(x+=7,h>>>=7),(h&15)===0&&(x+=4,h>>>=4),(h&3)===0&&(x+=2,h>>>=2),(h&1)===0&&x++,x},i.prototype.bitLength=function(){var l=this.words[this.length-1],h=this._countBits(l);return(this.length-1)*26+h};function m(T){for(var l=new Array(T.bitLength()),h=0;h<l.length;h++){var x=h/26|0,w=h%26;l[h]=(T.words[x]&1<<w)>>>w}return l}i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var l=0,h=0;h<this.length;h++){var x=this._zeroBits(this.words[h]);if(l+=x,x!==26)break}return l},i.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},i.prototype.toTwos=function(l){return this.negative!==0?this.abs().inotn(l).iaddn(1):this.clone()},i.prototype.fromTwos=function(l){return this.testn(l-1)?this.notn(l).iaddn(1).ineg():this.clone()},i.prototype.isNeg=function(){return this.negative!==0},i.prototype.neg=function(){return this.clone().ineg()},i.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},i.prototype.iuor=function(l){for(;this.length<l.length;)this.words[this.length++]=0;for(var h=0;h<l.length;h++)this.words[h]=this.words[h]|l.words[h];return this.strip()},i.prototype.ior=function(l){return t((this.negative|l.negative)===0),this.iuor(l)},i.prototype.or=function(l){return this.length>l.length?this.clone().ior(l):l.clone().ior(this)},i.prototype.uor=function(l){return this.length>l.length?this.clone().iuor(l):l.clone().iuor(this)},i.prototype.iuand=function(l){var h;this.length>l.length?h=l:h=this;for(var x=0;x<h.length;x++)this.words[x]=this.words[x]&l.words[x];return this.length=h.length,this.strip()},i.prototype.iand=function(l){return t((this.negative|l.negative)===0),this.iuand(l)},i.prototype.and=function(l){return this.length>l.length?this.clone().iand(l):l.clone().iand(this)},i.prototype.uand=function(l){return this.length>l.length?this.clone().iuand(l):l.clone().iuand(this)},i.prototype.iuxor=function(l){var h,x;this.length>l.length?(h=this,x=l):(h=l,x=this);for(var w=0;w<x.length;w++)this.words[w]=h.words[w]^x.words[w];if(this!==h)for(;w<h.length;w++)this.words[w]=h.words[w];return this.length=h.length,this.strip()},i.prototype.ixor=function(l){return t((this.negative|l.negative)===0),this.iuxor(l)},i.prototype.xor=function(l){return this.length>l.length?this.clone().ixor(l):l.clone().ixor(this)},i.prototype.uxor=function(l){return this.length>l.length?this.clone().iuxor(l):l.clone().iuxor(this)},i.prototype.inotn=function(l){t(typeof l=="number"&&l>=0);var h=Math.ceil(l/26)|0,x=l%26;this._expand(h),x>0&&h--;for(var w=0;w<h;w++)this.words[w]=~this.words[w]&67108863;return x>0&&(this.words[w]=~this.words[w]&67108863>>26-x),this.strip()},i.prototype.notn=function(l){return this.clone().inotn(l)},i.prototype.setn=function(l,h){t(typeof l=="number"&&l>=0);var x=l/26|0,w=l%26;return this._expand(x+1),h?this.words[x]=this.words[x]|1<<w:this.words[x]=this.words[x]&~(1<<w),this.strip()},i.prototype.iadd=function(l){var h;if(this.negative!==0&&l.negative===0)return this.negative=0,h=this.isub(l),this.negative^=1,this._normSign();if(this.negative===0&&l.negative!==0)return l.negative=0,h=this.isub(l),l.negative=1,h._normSign();var x,w;this.length>l.length?(x=this,w=l):(x=l,w=this);for(var g=0,v=0;v<w.length;v++)h=(x.words[v]|0)+(w.words[v]|0)+g,this.words[v]=h&67108863,g=h>>>26;for(;g!==0&&v<x.length;v++)h=(x.words[v]|0)+g,this.words[v]=h&67108863,g=h>>>26;if(this.length=x.length,g!==0)this.words[this.length]=g,this.length++;else if(x!==this)for(;v<x.length;v++)this.words[v]=x.words[v];return this},i.prototype.add=function(l){var h;return l.negative!==0&&this.negative===0?(l.negative=0,h=this.sub(l),l.negative^=1,h):l.negative===0&&this.negative!==0?(this.negative=0,h=l.sub(this),this.negative=1,h):this.length>l.length?this.clone().iadd(l):l.clone().iadd(this)},i.prototype.isub=function(l){if(l.negative!==0){l.negative=0;var h=this.iadd(l);return l.negative=1,h._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(l),this.negative=1,this._normSign();var x=this.cmp(l);if(x===0)return this.negative=0,this.length=1,this.words[0]=0,this;var w,g;x>0?(w=this,g=l):(w=l,g=this);for(var v=0,C=0;C<g.length;C++)h=(w.words[C]|0)-(g.words[C]|0)+v,v=h>>26,this.words[C]=h&67108863;for(;v!==0&&C<w.length;C++)h=(w.words[C]|0)+v,v=h>>26,this.words[C]=h&67108863;if(v===0&&C<w.length&&w!==this)for(;C<w.length;C++)this.words[C]=w.words[C];return this.length=Math.max(this.length,C),w!==this&&(this.negative=1),this.strip()},i.prototype.sub=function(l){return this.clone().isub(l)};function y(T,l,h){h.negative=l.negative^T.negative;var x=T.length+l.length|0;h.length=x,x=x-1|0;var w=T.words[0]|0,g=l.words[0]|0,v=w*g,C=v&67108863,b=v/67108864|0;h.words[0]=C;for(var d=1;d<x;d++){for(var E=b>>>26,U=b&67108863,I=Math.min(d,l.length-1),D=Math.max(0,d-T.length+1);D<=I;D++){var H=d-D|0;w=T.words[H]|0,g=l.words[D]|0,v=w*g+U,E+=v/67108864|0,U=v&67108863}h.words[d]=U|0,b=E|0}return b!==0?h.words[d]=b|0:h.length--,h.strip()}var _=function(l,h,x){var w=l.words,g=h.words,v=x.words,C=0,b,d,E,U=w[0]|0,I=U&8191,D=U>>>13,H=w[1]|0,V=H&8191,B=H>>>13,me=w[2]|0,ie=me&8191,R=me>>>13,Y=w[3]|0,k=Y&8191,j=Y>>>13,J=w[4]|0,K=J&8191,z=J>>>13,ge=w[5]|0,re=ge&8191,Me=ge>>>13,rv=w[6]|0,Ie=rv&8191,Ne=rv>>>13,nv=w[7]|0,Le=nv&8191,De=nv>>>13,iv=w[8]|0,Be=iv&8191,je=iv>>>13,sv=w[9]|0,Fe=sv&8191,$e=sv>>>13,ov=g[0]|0,He=ov&8191,Ue=ov>>>13,av=g[1]|0,qe=av&8191,We=av>>>13,cv=g[2]|0,Ge=cv&8191,ze=cv>>>13,lv=g[3]|0,Ve=lv&8191,Ke=lv>>>13,uv=g[4]|0,Ye=uv&8191,Xe=uv>>>13,pv=g[5]|0,Je=pv&8191,Qe=pv>>>13,fv=g[6]|0,Ze=fv&8191,et=fv>>>13,dv=g[7]|0,tt=dv&8191,rt=dv>>>13,hv=g[8]|0,nt=hv&8191,it=hv>>>13,mv=g[9]|0,st=mv&8191,ot=mv>>>13;x.negative=l.negative^h.negative,x.length=19,b=Math.imul(I,He),d=Math.imul(I,Ue),d=d+Math.imul(D,He)|0,E=Math.imul(D,Ue);var rp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(rp>>>26)|0,rp&=67108863,b=Math.imul(V,He),d=Math.imul(V,Ue),d=d+Math.imul(B,He)|0,E=Math.imul(B,Ue),b=b+Math.imul(I,qe)|0,d=d+Math.imul(I,We)|0,d=d+Math.imul(D,qe)|0,E=E+Math.imul(D,We)|0;var np=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(np>>>26)|0,np&=67108863,b=Math.imul(ie,He),d=Math.imul(ie,Ue),d=d+Math.imul(R,He)|0,E=Math.imul(R,Ue),b=b+Math.imul(V,qe)|0,d=d+Math.imul(V,We)|0,d=d+Math.imul(B,qe)|0,E=E+Math.imul(B,We)|0,b=b+Math.imul(I,Ge)|0,d=d+Math.imul(I,ze)|0,d=d+Math.imul(D,Ge)|0,E=E+Math.imul(D,ze)|0;var ip=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(ip>>>26)|0,ip&=67108863,b=Math.imul(k,He),d=Math.imul(k,Ue),d=d+Math.imul(j,He)|0,E=Math.imul(j,Ue),b=b+Math.imul(ie,qe)|0,d=d+Math.imul(ie,We)|0,d=d+Math.imul(R,qe)|0,E=E+Math.imul(R,We)|0,b=b+Math.imul(V,Ge)|0,d=d+Math.imul(V,ze)|0,d=d+Math.imul(B,Ge)|0,E=E+Math.imul(B,ze)|0,b=b+Math.imul(I,Ve)|0,d=d+Math.imul(I,Ke)|0,d=d+Math.imul(D,Ve)|0,E=E+Math.imul(D,Ke)|0;var sp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(sp>>>26)|0,sp&=67108863,b=Math.imul(K,He),d=Math.imul(K,Ue),d=d+Math.imul(z,He)|0,E=Math.imul(z,Ue),b=b+Math.imul(k,qe)|0,d=d+Math.imul(k,We)|0,d=d+Math.imul(j,qe)|0,E=E+Math.imul(j,We)|0,b=b+Math.imul(ie,Ge)|0,d=d+Math.imul(ie,ze)|0,d=d+Math.imul(R,Ge)|0,E=E+Math.imul(R,ze)|0,b=b+Math.imul(V,Ve)|0,d=d+Math.imul(V,Ke)|0,d=d+Math.imul(B,Ve)|0,E=E+Math.imul(B,Ke)|0,b=b+Math.imul(I,Ye)|0,d=d+Math.imul(I,Xe)|0,d=d+Math.imul(D,Ye)|0,E=E+Math.imul(D,Xe)|0;var op=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(op>>>26)|0,op&=67108863,b=Math.imul(re,He),d=Math.imul(re,Ue),d=d+Math.imul(Me,He)|0,E=Math.imul(Me,Ue),b=b+Math.imul(K,qe)|0,d=d+Math.imul(K,We)|0,d=d+Math.imul(z,qe)|0,E=E+Math.imul(z,We)|0,b=b+Math.imul(k,Ge)|0,d=d+Math.imul(k,ze)|0,d=d+Math.imul(j,Ge)|0,E=E+Math.imul(j,ze)|0,b=b+Math.imul(ie,Ve)|0,d=d+Math.imul(ie,Ke)|0,d=d+Math.imul(R,Ve)|0,E=E+Math.imul(R,Ke)|0,b=b+Math.imul(V,Ye)|0,d=d+Math.imul(V,Xe)|0,d=d+Math.imul(B,Ye)|0,E=E+Math.imul(B,Xe)|0,b=b+Math.imul(I,Je)|0,d=d+Math.imul(I,Qe)|0,d=d+Math.imul(D,Je)|0,E=E+Math.imul(D,Qe)|0;var ap=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(ap>>>26)|0,ap&=67108863,b=Math.imul(Ie,He),d=Math.imul(Ie,Ue),d=d+Math.imul(Ne,He)|0,E=Math.imul(Ne,Ue),b=b+Math.imul(re,qe)|0,d=d+Math.imul(re,We)|0,d=d+Math.imul(Me,qe)|0,E=E+Math.imul(Me,We)|0,b=b+Math.imul(K,Ge)|0,d=d+Math.imul(K,ze)|0,d=d+Math.imul(z,Ge)|0,E=E+Math.imul(z,ze)|0,b=b+Math.imul(k,Ve)|0,d=d+Math.imul(k,Ke)|0,d=d+Math.imul(j,Ve)|0,E=E+Math.imul(j,Ke)|0,b=b+Math.imul(ie,Ye)|0,d=d+Math.imul(ie,Xe)|0,d=d+Math.imul(R,Ye)|0,E=E+Math.imul(R,Xe)|0,b=b+Math.imul(V,Je)|0,d=d+Math.imul(V,Qe)|0,d=d+Math.imul(B,Je)|0,E=E+Math.imul(B,Qe)|0,b=b+Math.imul(I,Ze)|0,d=d+Math.imul(I,et)|0,d=d+Math.imul(D,Ze)|0,E=E+Math.imul(D,et)|0;var cp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(cp>>>26)|0,cp&=67108863,b=Math.imul(Le,He),d=Math.imul(Le,Ue),d=d+Math.imul(De,He)|0,E=Math.imul(De,Ue),b=b+Math.imul(Ie,qe)|0,d=d+Math.imul(Ie,We)|0,d=d+Math.imul(Ne,qe)|0,E=E+Math.imul(Ne,We)|0,b=b+Math.imul(re,Ge)|0,d=d+Math.imul(re,ze)|0,d=d+Math.imul(Me,Ge)|0,E=E+Math.imul(Me,ze)|0,b=b+Math.imul(K,Ve)|0,d=d+Math.imul(K,Ke)|0,d=d+Math.imul(z,Ve)|0,E=E+Math.imul(z,Ke)|0,b=b+Math.imul(k,Ye)|0,d=d+Math.imul(k,Xe)|0,d=d+Math.imul(j,Ye)|0,E=E+Math.imul(j,Xe)|0,b=b+Math.imul(ie,Je)|0,d=d+Math.imul(ie,Qe)|0,d=d+Math.imul(R,Je)|0,E=E+Math.imul(R,Qe)|0,b=b+Math.imul(V,Ze)|0,d=d+Math.imul(V,et)|0,d=d+Math.imul(B,Ze)|0,E=E+Math.imul(B,et)|0,b=b+Math.imul(I,tt)|0,d=d+Math.imul(I,rt)|0,d=d+Math.imul(D,tt)|0,E=E+Math.imul(D,rt)|0;var lp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(lp>>>26)|0,lp&=67108863,b=Math.imul(Be,He),d=Math.imul(Be,Ue),d=d+Math.imul(je,He)|0,E=Math.imul(je,Ue),b=b+Math.imul(Le,qe)|0,d=d+Math.imul(Le,We)|0,d=d+Math.imul(De,qe)|0,E=E+Math.imul(De,We)|0,b=b+Math.imul(Ie,Ge)|0,d=d+Math.imul(Ie,ze)|0,d=d+Math.imul(Ne,Ge)|0,E=E+Math.imul(Ne,ze)|0,b=b+Math.imul(re,Ve)|0,d=d+Math.imul(re,Ke)|0,d=d+Math.imul(Me,Ve)|0,E=E+Math.imul(Me,Ke)|0,b=b+Math.imul(K,Ye)|0,d=d+Math.imul(K,Xe)|0,d=d+Math.imul(z,Ye)|0,E=E+Math.imul(z,Xe)|0,b=b+Math.imul(k,Je)|0,d=d+Math.imul(k,Qe)|0,d=d+Math.imul(j,Je)|0,E=E+Math.imul(j,Qe)|0,b=b+Math.imul(ie,Ze)|0,d=d+Math.imul(ie,et)|0,d=d+Math.imul(R,Ze)|0,E=E+Math.imul(R,et)|0,b=b+Math.imul(V,tt)|0,d=d+Math.imul(V,rt)|0,d=d+Math.imul(B,tt)|0,E=E+Math.imul(B,rt)|0,b=b+Math.imul(I,nt)|0,d=d+Math.imul(I,it)|0,d=d+Math.imul(D,nt)|0,E=E+Math.imul(D,it)|0;var up=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(up>>>26)|0,up&=67108863,b=Math.imul(Fe,He),d=Math.imul(Fe,Ue),d=d+Math.imul($e,He)|0,E=Math.imul($e,Ue),b=b+Math.imul(Be,qe)|0,d=d+Math.imul(Be,We)|0,d=d+Math.imul(je,qe)|0,E=E+Math.imul(je,We)|0,b=b+Math.imul(Le,Ge)|0,d=d+Math.imul(Le,ze)|0,d=d+Math.imul(De,Ge)|0,E=E+Math.imul(De,ze)|0,b=b+Math.imul(Ie,Ve)|0,d=d+Math.imul(Ie,Ke)|0,d=d+Math.imul(Ne,Ve)|0,E=E+Math.imul(Ne,Ke)|0,b=b+Math.imul(re,Ye)|0,d=d+Math.imul(re,Xe)|0,d=d+Math.imul(Me,Ye)|0,E=E+Math.imul(Me,Xe)|0,b=b+Math.imul(K,Je)|0,d=d+Math.imul(K,Qe)|0,d=d+Math.imul(z,Je)|0,E=E+Math.imul(z,Qe)|0,b=b+Math.imul(k,Ze)|0,d=d+Math.imul(k,et)|0,d=d+Math.imul(j,Ze)|0,E=E+Math.imul(j,et)|0,b=b+Math.imul(ie,tt)|0,d=d+Math.imul(ie,rt)|0,d=d+Math.imul(R,tt)|0,E=E+Math.imul(R,rt)|0,b=b+Math.imul(V,nt)|0,d=d+Math.imul(V,it)|0,d=d+Math.imul(B,nt)|0,E=E+Math.imul(B,it)|0,b=b+Math.imul(I,st)|0,d=d+Math.imul(I,ot)|0,d=d+Math.imul(D,st)|0,E=E+Math.imul(D,ot)|0;var pp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(pp>>>26)|0,pp&=67108863,b=Math.imul(Fe,qe),d=Math.imul(Fe,We),d=d+Math.imul($e,qe)|0,E=Math.imul($e,We),b=b+Math.imul(Be,Ge)|0,d=d+Math.imul(Be,ze)|0,d=d+Math.imul(je,Ge)|0,E=E+Math.imul(je,ze)|0,b=b+Math.imul(Le,Ve)|0,d=d+Math.imul(Le,Ke)|0,d=d+Math.imul(De,Ve)|0,E=E+Math.imul(De,Ke)|0,b=b+Math.imul(Ie,Ye)|0,d=d+Math.imul(Ie,Xe)|0,d=d+Math.imul(Ne,Ye)|0,E=E+Math.imul(Ne,Xe)|0,b=b+Math.imul(re,Je)|0,d=d+Math.imul(re,Qe)|0,d=d+Math.imul(Me,Je)|0,E=E+Math.imul(Me,Qe)|0,b=b+Math.imul(K,Ze)|0,d=d+Math.imul(K,et)|0,d=d+Math.imul(z,Ze)|0,E=E+Math.imul(z,et)|0,b=b+Math.imul(k,tt)|0,d=d+Math.imul(k,rt)|0,d=d+Math.imul(j,tt)|0,E=E+Math.imul(j,rt)|0,b=b+Math.imul(ie,nt)|0,d=d+Math.imul(ie,it)|0,d=d+Math.imul(R,nt)|0,E=E+Math.imul(R,it)|0,b=b+Math.imul(V,st)|0,d=d+Math.imul(V,ot)|0,d=d+Math.imul(B,st)|0,E=E+Math.imul(B,ot)|0;var fp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(fp>>>26)|0,fp&=67108863,b=Math.imul(Fe,Ge),d=Math.imul(Fe,ze),d=d+Math.imul($e,Ge)|0,E=Math.imul($e,ze),b=b+Math.imul(Be,Ve)|0,d=d+Math.imul(Be,Ke)|0,d=d+Math.imul(je,Ve)|0,E=E+Math.imul(je,Ke)|0,b=b+Math.imul(Le,Ye)|0,d=d+Math.imul(Le,Xe)|0,d=d+Math.imul(De,Ye)|0,E=E+Math.imul(De,Xe)|0,b=b+Math.imul(Ie,Je)|0,d=d+Math.imul(Ie,Qe)|0,d=d+Math.imul(Ne,Je)|0,E=E+Math.imul(Ne,Qe)|0,b=b+Math.imul(re,Ze)|0,d=d+Math.imul(re,et)|0,d=d+Math.imul(Me,Ze)|0,E=E+Math.imul(Me,et)|0,b=b+Math.imul(K,tt)|0,d=d+Math.imul(K,rt)|0,d=d+Math.imul(z,tt)|0,E=E+Math.imul(z,rt)|0,b=b+Math.imul(k,nt)|0,d=d+Math.imul(k,it)|0,d=d+Math.imul(j,nt)|0,E=E+Math.imul(j,it)|0,b=b+Math.imul(ie,st)|0,d=d+Math.imul(ie,ot)|0,d=d+Math.imul(R,st)|0,E=E+Math.imul(R,ot)|0;var dp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(dp>>>26)|0,dp&=67108863,b=Math.imul(Fe,Ve),d=Math.imul(Fe,Ke),d=d+Math.imul($e,Ve)|0,E=Math.imul($e,Ke),b=b+Math.imul(Be,Ye)|0,d=d+Math.imul(Be,Xe)|0,d=d+Math.imul(je,Ye)|0,E=E+Math.imul(je,Xe)|0,b=b+Math.imul(Le,Je)|0,d=d+Math.imul(Le,Qe)|0,d=d+Math.imul(De,Je)|0,E=E+Math.imul(De,Qe)|0,b=b+Math.imul(Ie,Ze)|0,d=d+Math.imul(Ie,et)|0,d=d+Math.imul(Ne,Ze)|0,E=E+Math.imul(Ne,et)|0,b=b+Math.imul(re,tt)|0,d=d+Math.imul(re,rt)|0,d=d+Math.imul(Me,tt)|0,E=E+Math.imul(Me,rt)|0,b=b+Math.imul(K,nt)|0,d=d+Math.imul(K,it)|0,d=d+Math.imul(z,nt)|0,E=E+Math.imul(z,it)|0,b=b+Math.imul(k,st)|0,d=d+Math.imul(k,ot)|0,d=d+Math.imul(j,st)|0,E=E+Math.imul(j,ot)|0;var hp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(hp>>>26)|0,hp&=67108863,b=Math.imul(Fe,Ye),d=Math.imul(Fe,Xe),d=d+Math.imul($e,Ye)|0,E=Math.imul($e,Xe),b=b+Math.imul(Be,Je)|0,d=d+Math.imul(Be,Qe)|0,d=d+Math.imul(je,Je)|0,E=E+Math.imul(je,Qe)|0,b=b+Math.imul(Le,Ze)|0,d=d+Math.imul(Le,et)|0,d=d+Math.imul(De,Ze)|0,E=E+Math.imul(De,et)|0,b=b+Math.imul(Ie,tt)|0,d=d+Math.imul(Ie,rt)|0,d=d+Math.imul(Ne,tt)|0,E=E+Math.imul(Ne,rt)|0,b=b+Math.imul(re,nt)|0,d=d+Math.imul(re,it)|0,d=d+Math.imul(Me,nt)|0,E=E+Math.imul(Me,it)|0,b=b+Math.imul(K,st)|0,d=d+Math.imul(K,ot)|0,d=d+Math.imul(z,st)|0,E=E+Math.imul(z,ot)|0;var mp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(mp>>>26)|0,mp&=67108863,b=Math.imul(Fe,Je),d=Math.imul(Fe,Qe),d=d+Math.imul($e,Je)|0,E=Math.imul($e,Qe),b=b+Math.imul(Be,Ze)|0,d=d+Math.imul(Be,et)|0,d=d+Math.imul(je,Ze)|0,E=E+Math.imul(je,et)|0,b=b+Math.imul(Le,tt)|0,d=d+Math.imul(Le,rt)|0,d=d+Math.imul(De,tt)|0,E=E+Math.imul(De,rt)|0,b=b+Math.imul(Ie,nt)|0,d=d+Math.imul(Ie,it)|0,d=d+Math.imul(Ne,nt)|0,E=E+Math.imul(Ne,it)|0,b=b+Math.imul(re,st)|0,d=d+Math.imul(re,ot)|0,d=d+Math.imul(Me,st)|0,E=E+Math.imul(Me,ot)|0;var gp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(gp>>>26)|0,gp&=67108863,b=Math.imul(Fe,Ze),d=Math.imul(Fe,et),d=d+Math.imul($e,Ze)|0,E=Math.imul($e,et),b=b+Math.imul(Be,tt)|0,d=d+Math.imul(Be,rt)|0,d=d+Math.imul(je,tt)|0,E=E+Math.imul(je,rt)|0,b=b+Math.imul(Le,nt)|0,d=d+Math.imul(Le,it)|0,d=d+Math.imul(De,nt)|0,E=E+Math.imul(De,it)|0,b=b+Math.imul(Ie,st)|0,d=d+Math.imul(Ie,ot)|0,d=d+Math.imul(Ne,st)|0,E=E+Math.imul(Ne,ot)|0;var vp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(vp>>>26)|0,vp&=67108863,b=Math.imul(Fe,tt),d=Math.imul(Fe,rt),d=d+Math.imul($e,tt)|0,E=Math.imul($e,rt),b=b+Math.imul(Be,nt)|0,d=d+Math.imul(Be,it)|0,d=d+Math.imul(je,nt)|0,E=E+Math.imul(je,it)|0,b=b+Math.imul(Le,st)|0,d=d+Math.imul(Le,ot)|0,d=d+Math.imul(De,st)|0,E=E+Math.imul(De,ot)|0;var xp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(xp>>>26)|0,xp&=67108863,b=Math.imul(Fe,nt),d=Math.imul(Fe,it),d=d+Math.imul($e,nt)|0,E=Math.imul($e,it),b=b+Math.imul(Be,st)|0,d=d+Math.imul(Be,ot)|0,d=d+Math.imul(je,st)|0,E=E+Math.imul(je,ot)|0;var yp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(yp>>>26)|0,yp&=67108863,b=Math.imul(Fe,st),d=Math.imul(Fe,ot),d=d+Math.imul($e,st)|0,E=Math.imul($e,ot);var _p=(C+b|0)+((d&8191)<<13)|0;return C=(E+(d>>>13)|0)+(_p>>>26)|0,_p&=67108863,v[0]=rp,v[1]=np,v[2]=ip,v[3]=sp,v[4]=op,v[5]=ap,v[6]=cp,v[7]=lp,v[8]=up,v[9]=pp,v[10]=fp,v[11]=dp,v[12]=hp,v[13]=mp,v[14]=gp,v[15]=vp,v[16]=xp,v[17]=yp,v[18]=_p,C!==0&&(v[19]=C,x.length++),x};Math.imul||(_=y);function S(T,l,h){h.negative=l.negative^T.negative,h.length=T.length+l.length;for(var x=0,w=0,g=0;g<h.length-1;g++){var v=w;w=0;for(var C=x&67108863,b=Math.min(g,l.length-1),d=Math.max(0,g-T.length+1);d<=b;d++){var E=g-d,U=T.words[E]|0,I=l.words[d]|0,D=U*I,H=D&67108863;v=v+(D/67108864|0)|0,H=H+C|0,C=H&67108863,v=v+(H>>>26)|0,w+=v>>>26,v&=67108863}h.words[g]=C,x=v,v=w}return x!==0?h.words[g]=x:h.length--,h.strip()}function A(T,l,h){var x=new P;return x.mulp(T,l,h)}i.prototype.mulTo=function(l,h){var x,w=this.length+l.length;return this.length===10&&l.length===10?x=_(this,l,h):w<63?x=y(this,l,h):w<1024?x=S(this,l,h):x=A(this,l,h),x};function P(T,l){this.x=T,this.y=l}P.prototype.makeRBT=function(l){for(var h=new Array(l),x=i.prototype._countBits(l)-1,w=0;w<l;w++)h[w]=this.revBin(w,x,l);return h},P.prototype.revBin=function(l,h,x){if(l===0||l===x-1)return l;for(var w=0,g=0;g<h;g++)w|=(l&1)<<h-g-1,l>>=1;return w},P.prototype.permute=function(l,h,x,w,g,v){for(var C=0;C<v;C++)w[C]=h[l[C]],g[C]=x[l[C]]},P.prototype.transform=function(l,h,x,w,g,v){this.permute(v,l,h,x,w,g);for(var C=1;C<g;C<<=1)for(var b=C<<1,d=Math.cos(2*Math.PI/b),E=Math.sin(2*Math.PI/b),U=0;U<g;U+=b)for(var I=d,D=E,H=0;H<C;H++){var V=x[U+H],B=w[U+H],me=x[U+H+C],ie=w[U+H+C],R=I*me-D*ie;ie=I*ie+D*me,me=R,x[U+H]=V+me,w[U+H]=B+ie,x[U+H+C]=V-me,w[U+H+C]=B-ie,H!==b&&(R=d*I-E*D,D=d*D+E*I,I=R)}},P.prototype.guessLen13b=function(l,h){var x=Math.max(h,l)|1,w=x&1,g=0;for(x=x/2|0;x;x=x>>>1)g++;return 1<<g+1+w},P.prototype.conjugate=function(l,h,x){if(!(x<=1))for(var w=0;w<x/2;w++){var g=l[w];l[w]=l[x-w-1],l[x-w-1]=g,g=h[w],h[w]=-h[x-w-1],h[x-w-1]=-g}},P.prototype.normalize13b=function(l,h){for(var x=0,w=0;w<h/2;w++){var g=Math.round(l[2*w+1]/h)*8192+Math.round(l[2*w]/h)+x;l[w]=g&67108863,g<67108864?x=0:x=g/67108864|0}return l},P.prototype.convert13b=function(l,h,x,w){for(var g=0,v=0;v<h;v++)g=g+(l[v]|0),x[2*v]=g&8191,g=g>>>13,x[2*v+1]=g&8191,g=g>>>13;for(v=2*h;v<w;++v)x[v]=0;t(g===0),t((g&-8192)===0)},P.prototype.stub=function(l){for(var h=new Array(l),x=0;x<l;x++)h[x]=0;return h},P.prototype.mulp=function(l,h,x){var w=2*this.guessLen13b(l.length,h.length),g=this.makeRBT(w),v=this.stub(w),C=new Array(w),b=new Array(w),d=new Array(w),E=new Array(w),U=new Array(w),I=new Array(w),D=x.words;D.length=w,this.convert13b(l.words,l.length,C,w),this.convert13b(h.words,h.length,E,w),this.transform(C,v,b,d,w,g),this.transform(E,v,U,I,w,g);for(var H=0;H<w;H++){var V=b[H]*U[H]-d[H]*I[H];d[H]=b[H]*I[H]+d[H]*U[H],b[H]=V}return this.conjugate(b,d,w),this.transform(b,d,D,v,w,g),this.conjugate(D,v,w),this.normalize13b(D,w),x.negative=l.negative^h.negative,x.length=l.length+h.length,x.strip()},i.prototype.mul=function(l){var h=new i(null);return h.words=new Array(this.length+l.length),this.mulTo(l,h)},i.prototype.mulf=function(l){var h=new i(null);return h.words=new Array(this.length+l.length),A(this,l,h)},i.prototype.imul=function(l){return this.clone().mulTo(l,this)},i.prototype.imuln=function(l){t(typeof l=="number"),t(l<67108864);for(var h=0,x=0;x<this.length;x++){var w=(this.words[x]|0)*l,g=(w&67108863)+(h&67108863);h>>=26,h+=w/67108864|0,h+=g>>>26,this.words[x]=g&67108863}return h!==0&&(this.words[x]=h,this.length++),this.length=l===0?1:this.length,this},i.prototype.muln=function(l){return this.clone().imuln(l)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(l){var h=m(l);if(h.length===0)return new i(1);for(var x=this,w=0;w<h.length&&h[w]===0;w++,x=x.sqr());if(++w<h.length)for(var g=x.sqr();w<h.length;w++,g=g.sqr())h[w]!==0&&(x=x.mul(g));return x},i.prototype.iushln=function(l){t(typeof l=="number"&&l>=0);var h=l%26,x=(l-h)/26,w=67108863>>>26-h<<26-h,g;if(h!==0){var v=0;for(g=0;g<this.length;g++){var C=this.words[g]&w,b=(this.words[g]|0)-C<<h;this.words[g]=b|v,v=C>>>26-h}v&&(this.words[g]=v,this.length++)}if(x!==0){for(g=this.length-1;g>=0;g--)this.words[g+x]=this.words[g];for(g=0;g<x;g++)this.words[g]=0;this.length+=x}return this.strip()},i.prototype.ishln=function(l){return t(this.negative===0),this.iushln(l)},i.prototype.iushrn=function(l,h,x){t(typeof l=="number"&&l>=0);var w;h?w=(h-h%26)/26:w=0;var g=l%26,v=Math.min((l-g)/26,this.length),C=67108863^67108863>>>g<<g,b=x;if(w-=v,w=Math.max(0,w),b){for(var d=0;d<v;d++)b.words[d]=this.words[d];b.length=v}if(v!==0)if(this.length>v)for(this.length-=v,d=0;d<this.length;d++)this.words[d]=this.words[d+v];else this.words[0]=0,this.length=1;var E=0;for(d=this.length-1;d>=0&&(E!==0||d>=w);d--){var U=this.words[d]|0;this.words[d]=E<<26-g|U>>>g,E=U&C}return b&&E!==0&&(b.words[b.length++]=E),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(l,h,x){return t(this.negative===0),this.iushrn(l,h,x)},i.prototype.shln=function(l){return this.clone().ishln(l)},i.prototype.ushln=function(l){return this.clone().iushln(l)},i.prototype.shrn=function(l){return this.clone().ishrn(l)},i.prototype.ushrn=function(l){return this.clone().iushrn(l)},i.prototype.testn=function(l){t(typeof l=="number"&&l>=0);var h=l%26,x=(l-h)/26,w=1<<h;if(this.length<=x)return!1;var g=this.words[x];return!!(g&w)},i.prototype.imaskn=function(l){t(typeof l=="number"&&l>=0);var h=l%26,x=(l-h)/26;if(t(this.negative===0,"imaskn works only with positive numbers"),this.length<=x)return this;if(h!==0&&x++,this.length=Math.min(x,this.length),h!==0){var w=67108863^67108863>>>h<<h;this.words[this.length-1]&=w}return this.length===0&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.maskn=function(l){return this.clone().imaskn(l)},i.prototype.iaddn=function(l){return t(typeof l=="number"),t(l<67108864),l<0?this.isubn(-l):this.negative!==0?this.length===1&&(this.words[0]|0)<l?(this.words[0]=l-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(l),this.negative=1,this):this._iaddn(l)},i.prototype._iaddn=function(l){this.words[0]+=l;for(var h=0;h<this.length&&this.words[h]>=67108864;h++)this.words[h]-=67108864,h===this.length-1?this.words[h+1]=1:this.words[h+1]++;return this.length=Math.max(this.length,h+1),this},i.prototype.isubn=function(l){if(t(typeof l=="number"),t(l<67108864),l<0)return this.iaddn(-l);if(this.negative!==0)return this.negative=0,this.iaddn(l),this.negative=1,this;if(this.words[0]-=l,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var h=0;h<this.length&&this.words[h]<0;h++)this.words[h]+=67108864,this.words[h+1]-=1;return this.strip()},i.prototype.addn=function(l){return this.clone().iaddn(l)},i.prototype.subn=function(l){return this.clone().isubn(l)},i.prototype.iabs=function(){return this.negative=0,this},i.prototype.abs=function(){return this.clone().iabs()},i.prototype._ishlnsubmul=function(l,h,x){var w=l.length+x,g;this._expand(w);var v,C=0;for(g=0;g<l.length;g++){v=(this.words[g+x]|0)+C;var b=(l.words[g]|0)*h;v-=b&67108863,C=(v>>26)-(b/67108864|0),this.words[g+x]=v&67108863}for(;g<this.length-x;g++)v=(this.words[g+x]|0)+C,C=v>>26,this.words[g+x]=v&67108863;if(C===0)return this.strip();for(t(C===-1),C=0,g=0;g<this.length;g++)v=-(this.words[g]|0)+C,C=v>>26,this.words[g]=v&67108863;return this.negative=1,this.strip()},i.prototype._wordDiv=function(l,h){var x=this.length-l.length,w=this.clone(),g=l,v=g.words[g.length-1]|0,C=this._countBits(v);x=26-C,x!==0&&(g=g.ushln(x),w.iushln(x),v=g.words[g.length-1]|0);var b=w.length-g.length,d;if(h!=="mod"){d=new i(null),d.length=b+1,d.words=new Array(d.length);for(var E=0;E<d.length;E++)d.words[E]=0}var U=w.clone()._ishlnsubmul(g,1,b);U.negative===0&&(w=U,d&&(d.words[b]=1));for(var I=b-1;I>=0;I--){var D=(w.words[g.length+I]|0)*67108864+(w.words[g.length+I-1]|0);for(D=Math.min(D/v|0,67108863),w._ishlnsubmul(g,D,I);w.negative!==0;)D--,w.negative=0,w._ishlnsubmul(g,1,I),w.isZero()||(w.negative^=1);d&&(d.words[I]=D)}return d&&d.strip(),w.strip(),h!=="div"&&x!==0&&w.iushrn(x),{div:d||null,mod:w}},i.prototype.divmod=function(l,h,x){if(t(!l.isZero()),this.isZero())return{div:new i(0),mod:new i(0)};var w,g,v;return this.negative!==0&&l.negative===0?(v=this.neg().divmod(l,h),h!=="mod"&&(w=v.div.neg()),h!=="div"&&(g=v.mod.neg(),x&&g.negative!==0&&g.iadd(l)),{div:w,mod:g}):this.negative===0&&l.negative!==0?(v=this.divmod(l.neg(),h),h!=="mod"&&(w=v.div.neg()),{div:w,mod:v.mod}):(this.negative&l.negative)!==0?(v=this.neg().divmod(l.neg(),h),h!=="div"&&(g=v.mod.neg(),x&&g.negative!==0&&g.isub(l)),{div:v.div,mod:g}):l.length>this.length||this.cmp(l)<0?{div:new i(0),mod:this}:l.length===1?h==="div"?{div:this.divn(l.words[0]),mod:null}:h==="mod"?{div:null,mod:new i(this.modn(l.words[0]))}:{div:this.divn(l.words[0]),mod:new i(this.modn(l.words[0]))}:this._wordDiv(l,h)},i.prototype.div=function(l){return this.divmod(l,"div",!1).div},i.prototype.mod=function(l){return this.divmod(l,"mod",!1).mod},i.prototype.umod=function(l){return this.divmod(l,"mod",!0).mod},i.prototype.divRound=function(l){var h=this.divmod(l);if(h.mod.isZero())return h.div;var x=h.div.negative!==0?h.mod.isub(l):h.mod,w=l.ushrn(1),g=l.andln(1),v=x.cmp(w);return v<0||g===1&&v===0?h.div:h.div.negative!==0?h.div.isubn(1):h.div.iaddn(1)},i.prototype.modn=function(l){t(l<=67108863);for(var h=(1<<26)%l,x=0,w=this.length-1;w>=0;w--)x=(h*x+(this.words[w]|0))%l;return x},i.prototype.idivn=function(l){t(l<=67108863);for(var h=0,x=this.length-1;x>=0;x--){var w=(this.words[x]|0)+h*67108864;this.words[x]=w/l|0,h=w%l}return this.strip()},i.prototype.divn=function(l){return this.clone().idivn(l)},i.prototype.egcd=function(l){t(l.negative===0),t(!l.isZero());var h=this,x=l.clone();h.negative!==0?h=h.umod(l):h=h.clone();for(var w=new i(1),g=new i(0),v=new i(0),C=new i(1),b=0;h.isEven()&&x.isEven();)h.iushrn(1),x.iushrn(1),++b;for(var d=x.clone(),E=h.clone();!h.isZero();){for(var U=0,I=1;(h.words[0]&I)===0&&U<26;++U,I<<=1);if(U>0)for(h.iushrn(U);U-- >0;)(w.isOdd()||g.isOdd())&&(w.iadd(d),g.isub(E)),w.iushrn(1),g.iushrn(1);for(var D=0,H=1;(x.words[0]&H)===0&&D<26;++D,H<<=1);if(D>0)for(x.iushrn(D);D-- >0;)(v.isOdd()||C.isOdd())&&(v.iadd(d),C.isub(E)),v.iushrn(1),C.iushrn(1);h.cmp(x)>=0?(h.isub(x),w.isub(v),g.isub(C)):(x.isub(h),v.isub(w),C.isub(g))}return{a:v,b:C,gcd:x.iushln(b)}},i.prototype._invmp=function(l){t(l.negative===0),t(!l.isZero());var h=this,x=l.clone();h.negative!==0?h=h.umod(l):h=h.clone();for(var w=new i(1),g=new i(0),v=x.clone();h.cmpn(1)>0&&x.cmpn(1)>0;){for(var C=0,b=1;(h.words[0]&b)===0&&C<26;++C,b<<=1);if(C>0)for(h.iushrn(C);C-- >0;)w.isOdd()&&w.iadd(v),w.iushrn(1);for(var d=0,E=1;(x.words[0]&E)===0&&d<26;++d,E<<=1);if(d>0)for(x.iushrn(d);d-- >0;)g.isOdd()&&g.iadd(v),g.iushrn(1);h.cmp(x)>=0?(h.isub(x),w.isub(g)):(x.isub(h),g.isub(w))}var U;return h.cmpn(1)===0?U=w:U=g,U.cmpn(0)<0&&U.iadd(l),U},i.prototype.gcd=function(l){if(this.isZero())return l.abs();if(l.isZero())return this.abs();var h=this.clone(),x=l.clone();h.negative=0,x.negative=0;for(var w=0;h.isEven()&&x.isEven();w++)h.iushrn(1),x.iushrn(1);do{for(;h.isEven();)h.iushrn(1);for(;x.isEven();)x.iushrn(1);var g=h.cmp(x);if(g<0){var v=h;h=x,x=v}else if(g===0||x.cmpn(1)===0)break;h.isub(x)}while(!0);return x.iushln(w)},i.prototype.invm=function(l){return this.egcd(l).a.umod(l)},i.prototype.isEven=function(){return(this.words[0]&1)===0},i.prototype.isOdd=function(){return(this.words[0]&1)===1},i.prototype.andln=function(l){return this.words[0]&l},i.prototype.bincn=function(l){t(typeof l=="number");var h=l%26,x=(l-h)/26,w=1<<h;if(this.length<=x)return this._expand(x+1),this.words[x]|=w,this;for(var g=w,v=x;g!==0&&v<this.length;v++){var C=this.words[v]|0;C+=g,g=C>>>26,C&=67108863,this.words[v]=C}return g!==0&&(this.words[v]=g,this.length++),this},i.prototype.isZero=function(){return this.length===1&&this.words[0]===0},i.prototype.cmpn=function(l){var h=l<0;if(this.negative!==0&&!h)return-1;if(this.negative===0&&h)return 1;this.strip();var x;if(this.length>1)x=1;else{h&&(l=-l),t(l<=67108863,"Number is too big");var w=this.words[0]|0;x=w===l?0:w<l?-1:1}return this.negative!==0?-x|0:x},i.prototype.cmp=function(l){if(this.negative!==0&&l.negative===0)return-1;if(this.negative===0&&l.negative!==0)return 1;var h=this.ucmp(l);return this.negative!==0?-h|0:h},i.prototype.ucmp=function(l){if(this.length>l.length)return 1;if(this.length<l.length)return-1;for(var h=0,x=this.length-1;x>=0;x--){var w=this.words[x]|0,g=l.words[x]|0;if(w!==g){w<g?h=-1:w>g&&(h=1);break}}return h},i.prototype.gtn=function(l){return this.cmpn(l)===1},i.prototype.gt=function(l){return this.cmp(l)===1},i.prototype.gten=function(l){return this.cmpn(l)>=0},i.prototype.gte=function(l){return this.cmp(l)>=0},i.prototype.ltn=function(l){return this.cmpn(l)===-1},i.prototype.lt=function(l){return this.cmp(l)===-1},i.prototype.lten=function(l){return this.cmpn(l)<=0},i.prototype.lte=function(l){return this.cmp(l)<=0},i.prototype.eqn=function(l){return this.cmpn(l)===0},i.prototype.eq=function(l){return this.cmp(l)===0},i.red=function(l){return new M(l)},i.prototype.toRed=function(l){return t(!this.red,"Already a number in reduction context"),t(this.negative===0,"red works only with positives"),l.convertTo(this)._forceRed(l)},i.prototype.fromRed=function(){return t(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(l){return this.red=l,this},i.prototype.forceRed=function(l){return t(!this.red,"Already a number in reduction context"),this._forceRed(l)},i.prototype.redAdd=function(l){return t(this.red,"redAdd works only with red numbers"),this.red.add(this,l)},i.prototype.redIAdd=function(l){return t(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,l)},i.prototype.redSub=function(l){return t(this.red,"redSub works only with red numbers"),this.red.sub(this,l)},i.prototype.redISub=function(l){return t(this.red,"redISub works only with red numbers"),this.red.isub(this,l)},i.prototype.redShl=function(l){return t(this.red,"redShl works only with red numbers"),this.red.shl(this,l)},i.prototype.redMul=function(l){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.mul(this,l)},i.prototype.redIMul=function(l){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,l),this.red.imul(this,l)},i.prototype.redSqr=function(){return t(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return t(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return t(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return t(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return t(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(l){return t(this.red&&!l.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,l)};var L={k256:null,p224:null,p192:null,p25519:null};function N(T,l){this.name=T,this.p=new i(l,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}N.prototype._tmp=function(){var l=new i(null);return l.words=new Array(Math.ceil(this.n/13)),l},N.prototype.ireduce=function(l){var h=l,x;do this.split(h,this.tmp),h=this.imulK(h),h=h.iadd(this.tmp),x=h.bitLength();while(x>this.n);var w=x<this.n?-1:h.ucmp(this.p);return w===0?(h.words[0]=0,h.length=1):w>0?h.isub(this.p):h.strip!==void 0?h.strip():h._strip(),h},N.prototype.split=function(l,h){l.iushrn(this.n,0,h)},N.prototype.imulK=function(l){return l.imul(this.k)};function $(){N.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n($,N),$.prototype.split=function(l,h){for(var x=4194303,w=Math.min(l.length,9),g=0;g<w;g++)h.words[g]=l.words[g];if(h.length=w,l.length<=9){l.words[0]=0,l.length=1;return}var v=l.words[9];for(h.words[h.length++]=v&x,g=10;g<l.length;g++){var C=l.words[g]|0;l.words[g-10]=(C&x)<<4|v>>>22,v=C}v>>>=22,l.words[g-10]=v,v===0&&l.length>10?l.length-=10:l.length-=9},$.prototype.imulK=function(l){l.words[l.length]=0,l.words[l.length+1]=0,l.length+=2;for(var h=0,x=0;x<l.length;x++){var w=l.words[x]|0;h+=w*977,l.words[x]=h&67108863,h=w*64+(h/67108864|0)}return l.words[l.length-1]===0&&(l.length--,l.words[l.length-1]===0&&l.length--),l};function W(){N.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(W,N);function q(){N.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(q,N);function G(){N.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(G,N),G.prototype.imulK=function(l){for(var h=0,x=0;x<l.length;x++){var w=(l.words[x]|0)*19+h,g=w&67108863;w>>>=26,l.words[x]=g,h=w}return h!==0&&(l.words[l.length++]=h),l},i._prime=function(l){if(L[l])return L[l];var h;if(l==="k256")h=new $;else if(l==="p224")h=new W;else if(l==="p192")h=new q;else if(l==="p25519")h=new G;else throw new Error("Unknown prime "+l);return L[l]=h,h};function M(T){if(typeof T=="string"){var l=i._prime(T);this.m=l.p,this.prime=l}else t(T.gtn(1),"modulus must be greater than 1"),this.m=T,this.prime=null}M.prototype._verify1=function(l){t(l.negative===0,"red works only with positives"),t(l.red,"red works only with red numbers")},M.prototype._verify2=function(l,h){t((l.negative|h.negative)===0,"red works only with positives"),t(l.red&&l.red===h.red,"red works only with red numbers")},M.prototype.imod=function(l){return this.prime?this.prime.ireduce(l)._forceRed(this):l.umod(this.m)._forceRed(this)},M.prototype.neg=function(l){return l.isZero()?l.clone():this.m.sub(l)._forceRed(this)},M.prototype.add=function(l,h){this._verify2(l,h);var x=l.add(h);return x.cmp(this.m)>=0&&x.isub(this.m),x._forceRed(this)},M.prototype.iadd=function(l,h){this._verify2(l,h);var x=l.iadd(h);return x.cmp(this.m)>=0&&x.isub(this.m),x},M.prototype.sub=function(l,h){this._verify2(l,h);var x=l.sub(h);return x.cmpn(0)<0&&x.iadd(this.m),x._forceRed(this)},M.prototype.isub=function(l,h){this._verify2(l,h);var x=l.isub(h);return x.cmpn(0)<0&&x.iadd(this.m),x},M.prototype.shl=function(l,h){return this._verify1(l),this.imod(l.ushln(h))},M.prototype.imul=function(l,h){return this._verify2(l,h),this.imod(l.imul(h))},M.prototype.mul=function(l,h){return this._verify2(l,h),this.imod(l.mul(h))},M.prototype.isqr=function(l){return this.imul(l,l.clone())},M.prototype.sqr=function(l){return this.mul(l,l)},M.prototype.sqrt=function(l){if(l.isZero())return l.clone();var h=this.m.andln(3);if(t(h%2===1),h===3){var x=this.m.add(new i(1)).iushrn(2);return this.pow(l,x)}for(var w=this.m.subn(1),g=0;!w.isZero()&&w.andln(1)===0;)g++,w.iushrn(1);t(!w.isZero());var v=new i(1).toRed(this),C=v.redNeg(),b=this.m.subn(1).iushrn(1),d=this.m.bitLength();for(d=new i(2*d*d).toRed(this);this.pow(d,b).cmp(C)!==0;)d.redIAdd(C);for(var E=this.pow(d,w),U=this.pow(l,w.addn(1).iushrn(1)),I=this.pow(l,w),D=g;I.cmp(v)!==0;){for(var H=I,V=0;H.cmp(v)!==0;V++)H=H.redSqr();t(V<D);var B=this.pow(E,new i(1).iushln(D-V-1));U=U.redMul(B),E=B.redSqr(),I=I.redMul(E),D=V}return U},M.prototype.invm=function(l){var h=l._invmp(this.m);return h.negative!==0?(h.negative=0,this.imod(h).redNeg()):this.imod(h)},M.prototype.pow=function(l,h){if(h.isZero())return new i(1).toRed(this);if(h.cmpn(1)===0)return l.clone();var x=4,w=new Array(1<<x);w[0]=new i(1).toRed(this),w[1]=l;for(var g=2;g<w.length;g++)w[g]=this.mul(w[g-1],l);var v=w[0],C=0,b=0,d=h.bitLength()%26;for(d===0&&(d=26),g=h.length-1;g>=0;g--){for(var E=h.words[g],U=d-1;U>=0;U--){var I=E>>U&1;if(v!==w[0]&&(v=this.sqr(v)),I===0&&C===0){b=0;continue}C<<=1,C|=I,b++,!(b!==x&&(g!==0||U!==0))&&(v=this.mul(v,w[C]),b=0,C=0)}d=26}return v},M.prototype.convertTo=function(l){var h=l.umod(this.m);return h===l?h.clone():h},M.prototype.convertFrom=function(l){var h=l.clone();return h.red=null,h},i.mont=function(l){return new F(l)};function F(T){M.call(this,T),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new i(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}n(F,M),F.prototype.convertTo=function(l){return this.imod(l.ushln(this.shift))},F.prototype.convertFrom=function(l){var h=this.imod(l.mul(this.rinv));return h.red=null,h},F.prototype.imul=function(l,h){if(l.isZero()||h.isZero())return l.words[0]=0,l.length=1,l;var x=l.imul(h),w=x.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),g=x.isub(w).iushrn(this.shift),v=g;return g.cmp(this.m)>=0?v=g.isub(this.m):g.cmpn(0)<0&&(v=g.iadd(this.m)),v._forceRed(this)},F.prototype.mul=function(l,h){if(l.isZero()||h.isZero())return new i(0)._forceRed(this);var x=l.mul(h),w=x.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),g=x.isub(w).iushrn(this.shift),v=g;return g.cmp(this.m)>=0?v=g.isub(this.m):g.cmpn(0)<0&&(v=g.iadd(this.m)),v._forceRed(this)},F.prototype.invm=function(l){var h=this.imod(l._invmp(this.m).mul(this.r2));return h._forceRed(this)}})(typeof jh>"u"||jh,cE)});var lE=O((wG,$h)=>{typeof Object.create=="function"?$h.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:$h.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}});var Gn=O((SG,Uh)=>{try{if(Hh=require("util"),typeof Hh.inherits!="function")throw"";Uh.exports=Hh.inherits}catch{Uh.exports=lE()}var Hh});var Gl=O((EG,uE)=>{"use strict";var Wl=require("buffer"),As=Wl.Buffer,pr={},fr;for(fr in Wl)Wl.hasOwnProperty(fr)&&(fr==="SlowBuffer"||fr==="Buffer"||(pr[fr]=Wl[fr]));var Rs=pr.Buffer={};for(fr in As)As.hasOwnProperty(fr)&&(fr==="allocUnsafe"||fr==="allocUnsafeSlow"||(Rs[fr]=As[fr]));pr.Buffer.prototype=As.prototype;(!Rs.from||Rs.from===Uint8Array.from)&&(Rs.from=function(r,e,t){if(typeof r=="number")throw new TypeError('The "value" argument must not be of type number. Received type '+typeof r);if(r&&typeof r.length>"u")throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r);return As(r,e,t)});Rs.alloc||(Rs.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError('The "size" argument must be of type number. Received type '+typeof r);if(r<0||r>=2*(1<<30))throw new RangeError('The value "'+r+'" is invalid for option "size"');var n=As(r);return!e||e.length===0?n.fill(0):typeof t=="string"?n.fill(e,t):n.fill(e),n});if(!pr.kStringMaxLength)try{pr.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch{}pr.constants||(pr.constants={MAX_LENGTH:pr.kMaxLength},pr.kStringMaxLength&&(pr.constants.MAX_STRING_LENGTH=pr.kStringMaxLength));uE.exports=pr});var zl=O(pE=>{"use strict";var oj=Gn();function dr(r){this._reporterState={obj:null,path:[],options:r||{},errors:[]}}pE.Reporter=dr;dr.prototype.isError=function(e){return e instanceof ks};dr.prototype.save=function(){let e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}};dr.prototype.restore=function(e){let t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)};dr.prototype.enterKey=function(e){return this._reporterState.path.push(e)};dr.prototype.exitKey=function(e){let t=this._reporterState;t.path=t.path.slice(0,e-1)};dr.prototype.leaveKey=function(e,t,n){let i=this._reporterState;this.exitKey(e),i.obj!==null&&(i.obj[t]=n)};dr.prototype.path=function(){return this._reporterState.path.join("/")};dr.prototype.enterObject=function(){let e=this._reporterState,t=e.obj;return e.obj={},t};dr.prototype.leaveObject=function(e){let t=this._reporterState,n=t.obj;return t.obj=e,n};dr.prototype.error=function(e){let t,n=this._reporterState,i=e instanceof ks;if(i?t=e:t=new ks(n.path.map(function(s){return"["+JSON.stringify(s)+"]"}).join(""),e.message||e,e.stack),!n.options.partial)throw t;return i||n.errors.push(t),t};dr.prototype.wrapResult=function(e){let t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e};function ks(r,e){this.path=r,this.rethrow(e)}oj(ks,Error);ks.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,ks),!this.stack)try{throw new Error(this.message)}catch(t){this.stack=t.stack}return this}});var Ms=O(qh=>{"use strict";var aj=Gn(),Vl=zl().Reporter,Os=Gl().Buffer;function hr(r,e){if(Vl.call(this,e),!Os.isBuffer(r)){this.error("Input not Buffer");return}this.base=r,this.offset=0,this.length=r.length}aj(hr,Vl);qh.DecoderBuffer=hr;hr.isDecoderBuffer=function(e){return e instanceof hr?!0:typeof e=="object"&&Os.isBuffer(e.base)&&e.constructor.name==="DecoderBuffer"&&typeof e.offset=="number"&&typeof e.length=="number"&&typeof e.save=="function"&&typeof e.restore=="function"&&typeof e.isEmpty=="function"&&typeof e.readUInt8=="function"&&typeof e.skip=="function"&&typeof e.raw=="function"};hr.prototype.save=function(){return{offset:this.offset,reporter:Vl.prototype.save.call(this)}};hr.prototype.restore=function(e){let t=new hr(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,Vl.prototype.restore.call(this,e.reporter),t};hr.prototype.isEmpty=function(){return this.offset===this.length};hr.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")};hr.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");let n=new hr(this.base);return n._reporterState=this._reporterState,n.offset=this.offset,n.length=this.offset+e,this.offset+=e,n};hr.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)};function Ps(r,e){if(Array.isArray(r))this.length=0,this.value=r.map(function(t){return Ps.isEncoderBuffer(t)||(t=new Ps(t,e)),this.length+=t.length,t},this);else if(typeof r=="number"){if(!(0<=r&&r<=255))return e.error("non-byte EncoderBuffer value");this.value=r,this.length=1}else if(typeof r=="string")this.value=r,this.length=Os.byteLength(r);else if(Os.isBuffer(r))this.value=r,this.length=r.length;else return e.error("Unsupported type: "+typeof r)}qh.EncoderBuffer=Ps;Ps.isEncoderBuffer=function(e){return e instanceof Ps?!0:typeof e=="object"&&e.constructor.name==="EncoderBuffer"&&typeof e.length=="number"&&typeof e.join=="function"};Ps.prototype.join=function(e,t){return e||(e=Os.alloc(this.length)),t||(t=0),this.length===0||(Array.isArray(this.value)?this.value.forEach(function(n){n.join(e,t),t+=n.length}):(typeof this.value=="number"?e[t]=this.value:typeof this.value=="string"?e.write(this.value,t):Os.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length)),e}});var hE=O((AG,dE)=>{dE.exports=fE;function fE(r,e){if(!r)throw new Error(e||"Assertion failed")}fE.equal=function(e,t,n){if(e!=t)throw new Error(n||"Assertion failed: "+e+" != "+t)}});var Kl=O((RG,gE)=>{"use strict";var cj=zl().Reporter,lj=Ms().EncoderBuffer,uj=Ms().DecoderBuffer,Pt=hE(),mE=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],pj=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(mE),fj=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function fe(r,e,t){let n={};this._baseState=n,n.name=t,n.enc=r,n.parent=e||null,n.children=null,n.tag=null,n.args=null,n.reverseArgs=null,n.choice=null,n.optional=!1,n.any=!1,n.obj=!1,n.use=null,n.useDecoder=null,n.key=null,n.default=null,n.explicit=null,n.implicit=null,n.contains=null,n.parent||(n.children=[],this._wrap())}gE.exports=fe;var dj=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];fe.prototype.clone=function(){let e=this._baseState,t={};dj.forEach(function(i){t[i]=e[i]});let n=new this.constructor(t.parent);return n._baseState=t,n};fe.prototype._wrap=function(){let e=this._baseState;pj.forEach(function(t){this[t]=function(){let i=new this.constructor(this);return e.children.push(i),i[t].apply(i,arguments)}},this)};fe.prototype._init=function(e){let t=this._baseState;Pt(t.parent===null),e.call(this),t.children=t.children.filter(function(n){return n._baseState.parent===this},this),Pt.equal(t.children.length,1,"Root node can have only one child")};fe.prototype._useArgs=function(e){let t=this._baseState,n=e.filter(function(i){return i instanceof this.constructor},this);e=e.filter(function(i){return!(i instanceof this.constructor)},this),n.length!==0&&(Pt(t.children===null),t.children=n,n.forEach(function(i){i._baseState.parent=this},this)),e.length!==0&&(Pt(t.args===null),t.args=e,t.reverseArgs=e.map(function(i){if(typeof i!="object"||i.constructor!==Object)return i;let s={};return Object.keys(i).forEach(function(o){o==(o|0)&&(o|=0);let a=i[o];s[a]=o}),s}))};fj.forEach(function(r){fe.prototype[r]=function(){let t=this._baseState;throw new Error(r+" not implemented for encoding: "+t.enc)}});mE.forEach(function(r){fe.prototype[r]=function(){let t=this._baseState,n=Array.prototype.slice.call(arguments);return Pt(t.tag===null),t.tag=r,this._useArgs(n),this}});fe.prototype.use=function(e){Pt(e);let t=this._baseState;return Pt(t.use===null),t.use=e,this};fe.prototype.optional=function(){let e=this._baseState;return e.optional=!0,this};fe.prototype.def=function(e){let t=this._baseState;return Pt(t.default===null),t.default=e,t.optional=!0,this};fe.prototype.explicit=function(e){let t=this._baseState;return Pt(t.explicit===null&&t.implicit===null),t.explicit=e,this};fe.prototype.implicit=function(e){let t=this._baseState;return Pt(t.explicit===null&&t.implicit===null),t.implicit=e,this};fe.prototype.obj=function(){let e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,t.length!==0&&this._useArgs(t),this};fe.prototype.key=function(e){let t=this._baseState;return Pt(t.key===null),t.key=e,this};fe.prototype.any=function(){let e=this._baseState;return e.any=!0,this};fe.prototype.choice=function(e){let t=this._baseState;return Pt(t.choice===null),t.choice=e,this._useArgs(Object.keys(e).map(function(n){return e[n]})),this};fe.prototype.contains=function(e){let t=this._baseState;return Pt(t.use===null),t.contains=e,this};fe.prototype._decode=function(e,t){let n=this._baseState;if(n.parent===null)return e.wrapResult(n.children[0]._decode(e,t));let i=n.default,s=!0,o=null;if(n.key!==null&&(o=e.enterKey(n.key)),n.optional){let c=null;if(n.explicit!==null?c=n.explicit:n.implicit!==null?c=n.implicit:n.tag!==null&&(c=n.tag),c===null&&!n.any){let u=e.save();try{n.choice===null?this._decodeGeneric(n.tag,e,t):this._decodeChoice(e,t),s=!0}catch{s=!1}e.restore(u)}else if(s=this._peekTag(e,c,n.any),e.isError(s))return s}let a;if(n.obj&&s&&(a=e.enterObject()),s){if(n.explicit!==null){let u=this._decodeTag(e,n.explicit);if(e.isError(u))return u;e=u}let c=e.offset;if(n.use===null&&n.choice===null){let u;n.any&&(u=e.save());let p=this._decodeTag(e,n.implicit!==null?n.implicit:n.tag,n.any);if(e.isError(p))return p;n.any?i=e.raw(u):e=p}if(t&&t.track&&n.tag!==null&&t.track(e.path(),c,e.length,"tagged"),t&&t.track&&n.tag!==null&&t.track(e.path(),e.offset,e.length,"content"),n.any||(n.choice===null?i=this._decodeGeneric(n.tag,e,t):i=this._decodeChoice(e,t)),e.isError(i))return i;if(!n.any&&n.choice===null&&n.children!==null&&n.children.forEach(function(p){p._decode(e,t)}),n.contains&&(n.tag==="octstr"||n.tag==="bitstr")){let u=new uj(i);i=this._getUse(n.contains,e._reporterState.obj)._decode(u,t)}}return n.obj&&s&&(i=e.leaveObject(a)),n.key!==null&&(i!==null||s===!0)?e.leaveKey(o,n.key,i):o!==null&&e.exitKey(o),i};fe.prototype._decodeGeneric=function(e,t,n){let i=this._baseState;return e==="seq"||e==="set"?null:e==="seqof"||e==="setof"?this._decodeList(t,e,i.args[0],n):/str$/.test(e)?this._decodeStr(t,e,n):e==="objid"&&i.args?this._decodeObjid(t,i.args[0],i.args[1],n):e==="objid"?this._decodeObjid(t,null,null,n):e==="gentime"||e==="utctime"?this._decodeTime(t,e,n):e==="null_"?this._decodeNull(t,n):e==="bool"?this._decodeBool(t,n):e==="objDesc"?this._decodeStr(t,e,n):e==="int"||e==="enum"?this._decodeInt(t,i.args&&i.args[0],n):i.use!==null?this._getUse(i.use,t._reporterState.obj)._decode(t,n):t.error("unknown tag: "+e)};fe.prototype._getUse=function(e,t){let n=this._baseState;return n.useDecoder=this._use(e,t),Pt(n.useDecoder._baseState.parent===null),n.useDecoder=n.useDecoder._baseState.children[0],n.implicit!==n.useDecoder._baseState.implicit&&(n.useDecoder=n.useDecoder.clone(),n.useDecoder._baseState.implicit=n.implicit),n.useDecoder};fe.prototype._decodeChoice=function(e,t){let n=this._baseState,i=null,s=!1;return Object.keys(n.choice).some(function(o){let a=e.save(),c=n.choice[o];try{let u=c._decode(e,t);if(e.isError(u))return!1;i={type:o,value:u},s=!0}catch{return e.restore(a),!1}return!0},this),s?i:e.error("Choice not matched")};fe.prototype._createEncoderBuffer=function(e){return new lj(e,this.reporter)};fe.prototype._encode=function(e,t,n){let i=this._baseState;if(i.default!==null&&i.default===e)return;let s=this._encodeValue(e,t,n);if(s!==void 0&&!this._skipDefault(s,t,n))return s};fe.prototype._encodeValue=function(e,t,n){let i=this._baseState;if(i.parent===null)return i.children[0]._encode(e,t||new cj);let s=null;if(this.reporter=t,i.optional&&e===void 0)if(i.default!==null)e=i.default;else return;let o=null,a=!1;if(i.any)s=this._createEncoderBuffer(e);else if(i.choice)s=this._encodeChoice(e,t);else if(i.contains)o=this._getUse(i.contains,n)._encode(e,t),a=!0;else if(i.children)o=i.children.map(function(c){if(c._baseState.tag==="null_")return c._encode(null,t,e);if(c._baseState.key===null)return t.error("Child should have a key");let u=t.enterKey(c._baseState.key);if(typeof e!="object")return t.error("Child expected, but input is not object");let p=c._encode(e[c._baseState.key],t,e);return t.leaveKey(u),p},this).filter(function(c){return c}),o=this._createEncoderBuffer(o);else if(i.tag==="seqof"||i.tag==="setof"){if(!(i.args&&i.args.length===1))return t.error("Too many args for : "+i.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");let c=this.clone();c._baseState.implicit=null,o=this._createEncoderBuffer(e.map(function(u){let p=this._baseState;return this._getUse(p.args[0],e)._encode(u,t)},c))}else i.use!==null?s=this._getUse(i.use,n)._encode(e,t):(o=this._encodePrimitive(i.tag,e),a=!0);if(!i.any&&i.choice===null){let c=i.implicit!==null?i.implicit:i.tag,u=i.implicit===null?"universal":"context";c===null?i.use===null&&t.error("Tag could be omitted only for .use()"):i.use===null&&(s=this._encodeComposite(c,a,u,o))}return i.explicit!==null&&(s=this._encodeComposite(i.explicit,!1,"context",s)),s};fe.prototype._encodeChoice=function(e,t){let n=this._baseState,i=n.choice[e.type];return i||Pt(!1,e.type+" not found in "+JSON.stringify(Object.keys(n.choice))),i._encode(e.value,t)};fe.prototype._encodePrimitive=function(e,t){let n=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if(e==="objid"&&n.args)return this._encodeObjid(t,n.reverseArgs[0],n.args[1]);if(e==="objid")return this._encodeObjid(t,null,null);if(e==="gentime"||e==="utctime")return this._encodeTime(t,e);if(e==="null_")return this._encodeNull();if(e==="int"||e==="enum")return this._encodeInt(t,n.args&&n.reverseArgs[0]);if(e==="bool")return this._encodeBool(t);if(e==="objDesc")return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)};fe.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)};fe.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(e)}});var Yl=O(vi=>{"use strict";function vE(r){let e={};return Object.keys(r).forEach(function(t){(t|0)==t&&(t=t|0);let n=r[t];e[n]=t}),e}vi.tagClass={0:"universal",1:"application",2:"context",3:"private"};vi.tagClassByName=vE(vi.tagClass);vi.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"};vi.tagByName=vE(vi.tag)});var Gh=O((OG,_E)=>{"use strict";var hj=Gn(),yn=Gl().Buffer,xE=Kl(),Wh=Yl();function yE(r){this.enc="der",this.name=r.name,this.entity=r,this.tree=new Rr,this.tree._init(r.body)}_E.exports=yE;yE.prototype.encode=function(e,t){return this.tree._encode(e,t).join()};function Rr(r){xE.call(this,"der",r)}hj(Rr,xE);Rr.prototype._encodeComposite=function(e,t,n,i){let s=mj(e,t,n,this.reporter);if(i.length<128){let c=yn.alloc(2);return c[0]=s,c[1]=i.length,this._createEncoderBuffer([c,i])}let o=1;for(let c=i.length;c>=256;c>>=8)o++;let a=yn.alloc(2+o);a[0]=s,a[1]=128|o;for(let c=1+o,u=i.length;u>0;c--,u>>=8)a[c]=u&255;return this._createEncoderBuffer([a,i])};Rr.prototype._encodeStr=function(e,t){if(t==="bitstr")return this._createEncoderBuffer([e.unused|0,e.data]);if(t==="bmpstr"){let n=yn.alloc(e.length*2);for(let i=0;i<e.length;i++)n.writeUInt16BE(e.charCodeAt(i),i*2);return this._createEncoderBuffer(n)}else return t==="numstr"?this._isNumstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: numstr supports only digits and space"):t==="printstr"?this._isPrintstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark"):/str$/.test(t)?this._createEncoderBuffer(e):t==="objDesc"?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: "+t+" unsupported")};Rr.prototype._encodeObjid=function(e,t,n){if(typeof e=="string"){if(!t)return this.reporter.error("string objid given, but no values map found");if(!t.hasOwnProperty(e))return this.reporter.error("objid not found in values map");e=t[e].split(/[\s.]+/g);for(let a=0;a<e.length;a++)e[a]|=0}else if(Array.isArray(e)){e=e.slice();for(let a=0;a<e.length;a++)e[a]|=0}if(!Array.isArray(e))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(e));if(!n){if(e[1]>=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,e[0]*40+e[1])}let i=0;for(let a=0;a<e.length;a++){let c=e[a];for(i++;c>=128;c>>=7)i++}let s=yn.alloc(i),o=s.length-1;for(let a=e.length-1;a>=0;a--){let c=e[a];for(s[o--]=c&127;(c>>=7)>0;)s[o--]=128|c&127}return this._createEncoderBuffer(s)};function mr(r){return r<10?"0"+r:r}Rr.prototype._encodeTime=function(e,t){let n,i=new Date(e);return t==="gentime"?n=[mr(i.getUTCFullYear()),mr(i.getUTCMonth()+1),mr(i.getUTCDate()),mr(i.getUTCHours()),mr(i.getUTCMinutes()),mr(i.getUTCSeconds()),"Z"].join(""):t==="utctime"?n=[mr(i.getUTCFullYear()%100),mr(i.getUTCMonth()+1),mr(i.getUTCDate()),mr(i.getUTCHours()),mr(i.getUTCMinutes()),mr(i.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(n,"octstr")};Rr.prototype._encodeNull=function(){return this._createEncoderBuffer("")};Rr.prototype._encodeInt=function(e,t){if(typeof e=="string"){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if(typeof e!="number"&&!yn.isBuffer(e)){let s=e.toArray();!e.sign&&s[0]&128&&s.unshift(0),e=yn.from(s)}if(yn.isBuffer(e)){let s=e.length;e.length===0&&s++;let o=yn.alloc(s);return e.copy(o),e.length===0&&(o[0]=0),this._createEncoderBuffer(o)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);let n=1;for(let s=e;s>=256;s>>=8)n++;let i=new Array(n);for(let s=i.length-1;s>=0;s--)i[s]=e&255,e>>=8;return i[0]&128&&i.unshift(0),this._createEncoderBuffer(yn.from(i))};Rr.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)};Rr.prototype._use=function(e,t){return typeof e=="function"&&(e=e(t)),e._getEncoder("der").tree};Rr.prototype._skipDefault=function(e,t,n){let i=this._baseState,s;if(i.default===null)return!1;let o=e.join();if(i.defaultBuffer===void 0&&(i.defaultBuffer=this._encodeValue(i.default,t,n).join()),o.length!==i.defaultBuffer.length)return!1;for(s=0;s<o.length;s++)if(o[s]!==i.defaultBuffer[s])return!1;return!0};function mj(r,e,t,n){let i;if(r==="seqof"?r="seq":r==="setof"&&(r="set"),Wh.tagByName.hasOwnProperty(r))i=Wh.tagByName[r];else if(typeof r=="number"&&(r|0)===r)i=r;else return n.error("Unknown tag: "+r);return i>=31?n.error("Multi-octet tag encoding unsupported"):(e||(i|=32),i|=Wh.tagClassByName[t||"universal"]<<6,i)}});var wE=O((PG,bE)=>{"use strict";var gj=Gn(),zh=Gh();function Vh(r){zh.call(this,r),this.enc="pem"}gj(Vh,zh);bE.exports=Vh;Vh.prototype.encode=function(e,t){let i=zh.prototype.encode.call(this,e).toString("base64"),s=["-----BEGIN "+t.label+"-----"];for(let o=0;o<i.length;o+=64)s.push(i.slice(o,o+64));return s.push("-----END "+t.label+"-----"),s.join(`
|
|
92
92
|
`)}});var Kh=O(EE=>{"use strict";var SE=EE;SE.der=Gh();SE.pem=wE()});var Xh=O((IG,OE)=>{"use strict";var vj=Gn(),xj=Fh(),TE=Ms().DecoderBuffer,AE=Kl(),CE=Yl();function RE(r){this.enc="der",this.name=r.name,this.entity=r,this.tree=new Jt,this.tree._init(r.body)}OE.exports=RE;RE.prototype.decode=function(e,t){return TE.isDecoderBuffer(e)||(e=new TE(e,t)),this.tree._decode(e,t)};function Jt(r){AE.call(this,"der",r)}vj(Jt,AE);Jt.prototype._peekTag=function(e,t,n){if(e.isEmpty())return!1;let i=e.save(),s=Yh(e,'Failed to peek tag: "'+t+'"');return e.isError(s)?s:(e.restore(i),s.tag===t||s.tagStr===t||s.tagStr+"of"===t||n)};Jt.prototype._decodeTag=function(e,t,n){let i=Yh(e,'Failed to decode tag of "'+t+'"');if(e.isError(i))return i;let s=kE(e,i.primitive,'Failed to get length of "'+t+'"');if(e.isError(s))return s;if(!n&&i.tag!==t&&i.tagStr!==t&&i.tagStr+"of"!==t)return e.error('Failed to match tag: "'+t+'"');if(i.primitive||s!==null)return e.skip(s,'Failed to match body of: "'+t+'"');let o=e.save(),a=this._skipUntilEnd(e,'Failed to skip indefinite length body: "'+this.tag+'"');return e.isError(a)?a:(s=e.offset-o.offset,e.restore(o),e.skip(s,'Failed to match body of: "'+t+'"'))};Jt.prototype._skipUntilEnd=function(e,t){for(;;){let n=Yh(e,t);if(e.isError(n))return n;let i=kE(e,n.primitive,t);if(e.isError(i))return i;let s;if(n.primitive||i!==null?s=e.skip(i):s=this._skipUntilEnd(e,t),e.isError(s))return s;if(n.tagStr==="end")break}};Jt.prototype._decodeList=function(e,t,n,i){let s=[];for(;!e.isEmpty();){let o=this._peekTag(e,"end");if(e.isError(o))return o;let a=n.decode(e,"der",i);if(e.isError(a)&&o)break;s.push(a)}return s};Jt.prototype._decodeStr=function(e,t){if(t==="bitstr"){let n=e.readUInt8();return e.isError(n)?n:{unused:n,data:e.raw()}}else if(t==="bmpstr"){let n=e.raw();if(n.length%2===1)return e.error("Decoding of string type: bmpstr length mismatch");let i="";for(let s=0;s<n.length/2;s++)i+=String.fromCharCode(n.readUInt16BE(s*2));return i}else if(t==="numstr"){let n=e.raw().toString("ascii");return this._isNumstr(n)?n:e.error("Decoding of string type: numstr unsupported characters")}else{if(t==="octstr")return e.raw();if(t==="objDesc")return e.raw();if(t==="printstr"){let n=e.raw().toString("ascii");return this._isPrintstr(n)?n:e.error("Decoding of string type: printstr unsupported characters")}else return/str$/.test(t)?e.raw().toString():e.error("Decoding of string type: "+t+" unsupported")}};Jt.prototype._decodeObjid=function(e,t,n){let i,s=[],o=0,a=0;for(;!e.isEmpty();)a=e.readUInt8(),o<<=7,o|=a&127,(a&128)===0&&(s.push(o),o=0);a&128&&s.push(o);let c=s[0]/40|0,u=s[0]%40;if(n?i=s:i=[c,u].concat(s.slice(1)),t){let p=t[i.join(" ")];p===void 0&&(p=t[i.join(".")]),p!==void 0&&(i=p)}return i};Jt.prototype._decodeTime=function(e,t){let n=e.raw().toString(),i,s,o,a,c,u;if(t==="gentime")i=n.slice(0,4)|0,s=n.slice(4,6)|0,o=n.slice(6,8)|0,a=n.slice(8,10)|0,c=n.slice(10,12)|0,u=n.slice(12,14)|0;else if(t==="utctime")i=n.slice(0,2)|0,s=n.slice(2,4)|0,o=n.slice(4,6)|0,a=n.slice(6,8)|0,c=n.slice(8,10)|0,u=n.slice(10,12)|0,i<70?i=2e3+i:i=1900+i;else return e.error("Decoding "+t+" time is not supported yet");return Date.UTC(i,s-1,o,a,c,u,0)};Jt.prototype._decodeNull=function(){return null};Jt.prototype._decodeBool=function(e){let t=e.readUInt8();return e.isError(t)?t:t!==0};Jt.prototype._decodeInt=function(e,t){let n=e.raw(),i=new xj(n);return t&&(i=t[i.toString(10)]||i),i};Jt.prototype._use=function(e,t){return typeof e=="function"&&(e=e(t)),e._getDecoder("der").tree};function Yh(r,e){let t=r.readUInt8(e);if(r.isError(t))return t;let n=CE.tagClass[t>>6],i=(t&32)===0;if((t&31)===31){let o=t;for(t=0;(o&128)===128;){if(o=r.readUInt8(e),r.isError(o))return o;t<<=7,t|=o&127}}else t&=31;let s=CE.tag[t];return{cls:n,primitive:i,tag:t,tagStr:s}}function kE(r,e,t){let n=r.readUInt8(t);if(r.isError(n))return n;if(!e&&n===128)return null;if((n&128)===0)return n;let i=n&127;if(i>4)return r.error("length octect is too long");n=0;for(let s=0;s<i;s++){n<<=8;let o=r.readUInt8(t);if(r.isError(o))return o;n|=o}return n}});var ME=O((NG,PE)=>{"use strict";var yj=Gn(),_j=Gl().Buffer,Jh=Xh();function Qh(r){Jh.call(this,r),this.enc="pem"}yj(Qh,Jh);PE.exports=Qh;Qh.prototype.decode=function(e,t){let n=e.toString().split(/[\r\n]+/g),i=t.label.toUpperCase(),s=/^-----(BEGIN|END) ([^-]+)-----$/,o=-1,a=-1;for(let p=0;p<n.length;p++){let f=n[p].match(s);if(f!==null&&f[2]===i)if(o===-1){if(f[1]!=="BEGIN")break;o=p}else{if(f[1]!=="END")break;a=p;break}}if(o===-1||a===-1)throw new Error("PEM section not found for: "+i);let c=n.slice(o+1,a).join("");c.replace(/[^a-z0-9+/=]+/gi,"");let u=_j.from(c,"base64");return Jh.prototype.decode.call(this,u,t)}});var Zh=O(NE=>{"use strict";var IE=NE;IE.der=Xh();IE.pem=ME()});var DE=O(LE=>{"use strict";var bj=Kh(),wj=Zh(),Sj=Gn(),Ej=LE;Ej.define=function(e,t){return new Is(e,t)};function Is(r,e){this.name=r,this.body=e,this.decoders={},this.encoders={}}Is.prototype._createNamed=function(e){let t=this.name;function n(i){this._initNamed(i,t)}return Sj(n,e),n.prototype._initNamed=function(s,o){e.call(this,s,o)},new n(this)};Is.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(wj[e])),this.decoders[e]};Is.prototype.decode=function(e,t,n){return this._getDecoder(t).decode(e,n)};Is.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(bj[e])),this.encoders[e]};Is.prototype.encode=function(e,t,n){return this._getEncoder(t).encode(e,n)}});var jE=O(BE=>{"use strict";var Xl=BE;Xl.Reporter=zl().Reporter;Xl.DecoderBuffer=Ms().DecoderBuffer;Xl.EncoderBuffer=Ms().EncoderBuffer;Xl.Node=Kl()});var HE=O($E=>{"use strict";var FE=$E;FE._reverse=function(e){let t={};return Object.keys(e).forEach(function(n){(n|0)==n&&(n=n|0);let i=e[n];t[i]=n}),t};FE.der=Yl()});var qE=O(UE=>{"use strict";var Ns=UE;Ns.bignum=Fh();Ns.define=DE().define;Ns.base=jE();Ns.constants=HE();Ns.decoders=Zh();Ns.encoders=Kh()});var Ls=O((em,GE)=>{var Jl=require("buffer"),qr=Jl.Buffer;function WE(r,e){for(var t in r)e[t]=r[t]}qr.from&&qr.alloc&&qr.allocUnsafe&&qr.allocUnsafeSlow?GE.exports=Jl:(WE(Jl,em),em.Buffer=xi);function xi(r,e,t){return qr(r,e,t)}xi.prototype=Object.create(qr.prototype);WE(qr,xi);xi.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return qr(r,e,t)};xi.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=qr(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};xi.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return qr(r)};xi.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return Jl.SlowBuffer(r)}});var tm=O(($G,zE)=>{var Ql=Ls().Buffer,Tj=require("stream"),Cj=require("util");function Zl(r){if(this.buffer=null,this.writable=!0,this.readable=!0,!r)return this.buffer=Ql.alloc(0),this;if(typeof r.pipe=="function")return this.buffer=Ql.alloc(0),r.pipe(this),this;if(r.length||typeof r=="object")return this.buffer=r,this.writable=!1,process.nextTick(function(){this.emit("end",r),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof r+")")}Cj.inherits(Zl,Tj);Zl.prototype.write=function(e){this.buffer=Ql.concat([this.buffer,Ql.from(e)]),this.emit("data",e)};Zl.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};zE.exports=Zl});var KE=O((HG,VE)=>{"use strict";function rm(r){var e=(r/8|0)+(r%8===0?0:1);return e}var Aj={ES256:rm(256),ES384:rm(384),ES512:rm(521)};function Rj(r){var e=Aj[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}VE.exports=Rj});var t1=O((UG,e1)=>{"use strict";var eu=Ls().Buffer,XE=KE(),tu=128,JE=0,kj=32,Oj=16,Pj=2,QE=Oj|kj|JE<<6,ru=Pj|JE<<6;function Mj(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ZE(r){if(eu.isBuffer(r))return r;if(typeof r=="string")return eu.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Ij(r,e){r=ZE(r);var t=XE(e),n=t+1,i=r.length,s=0;if(r[s++]!==QE)throw new Error('Could not find expected "seq"');var o=r[s++];if(o===(tu|1)&&(o=r[s++]),i-s<o)throw new Error('"seq" specified length of "'+o+'", only "'+(i-s)+'" remaining');if(r[s++]!==ru)throw new Error('Could not find expected "int" for "r"');var a=r[s++];if(i-s-2<a)throw new Error('"r" specified length of "'+a+'", only "'+(i-s-2)+'" available');if(n<a)throw new Error('"r" specified length of "'+a+'", max of "'+n+'" is acceptable');var c=s;if(s+=a,r[s++]!==ru)throw new Error('Could not find expected "int" for "s"');var u=r[s++];if(i-s!==u)throw new Error('"s" specified length of "'+u+'", expected "'+(i-s)+'"');if(n<u)throw new Error('"s" specified length of "'+u+'", max of "'+n+'" is acceptable');var p=s;if(s+=u,s!==i)throw new Error('Expected to consume entire buffer, but "'+(i-s)+'" bytes remain');var f=t-a,m=t-u,y=eu.allocUnsafe(f+a+m+u);for(s=0;s<f;++s)y[s]=0;r.copy(y,s,c+Math.max(-f,0),c+a),s=t;for(var _=s;s<_+m;++s)y[s]=0;return r.copy(y,s,p+Math.max(-m,0),p+u),y=y.toString("base64"),y=Mj(y),y}function YE(r,e,t){for(var n=0;e+n<t&&r[e+n]===0;)++n;var i=r[e+n]>=tu;return i&&--n,n}function Nj(r,e){r=ZE(r);var t=XE(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var i=YE(r,0,t),s=YE(r,t,r.length),o=t-i,a=t-s,c=2+o+1+1+a,u=c<tu,p=eu.allocUnsafe((u?2:3)+c),f=0;return p[f++]=QE,u?p[f++]=c:(p[f++]=tu|1,p[f++]=c&255),p[f++]=ru,p[f++]=o,i<0?(p[f++]=0,f+=r.copy(p,f,0,t)):f+=r.copy(p,f,i,t),p[f++]=ru,p[f++]=a,s<0?(p[f++]=0,r.copy(p,f,t)):r.copy(p,f,t+s),p}e1.exports={derToJose:Ij,joseToDer:Nj}});var n1=O((qG,r1)=>{"use strict";var Yo=require("buffer").Buffer,nm=require("buffer").SlowBuffer;r1.exports=nu;function nu(r,e){if(!Yo.isBuffer(r)||!Yo.isBuffer(e)||r.length!==e.length)return!1;for(var t=0,n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}nu.install=function(){Yo.prototype.equal=nm.prototype.equal=function(e){return nu(this,e)}};var Lj=Yo.prototype.equal,Dj=nm.prototype.equal;nu.restore=function(){Yo.prototype.equal=Lj,nm.prototype.equal=Dj}});var am=O((WG,f1)=>{var Bs=Ls().Buffer,gr=require("crypto"),s1=t1(),i1=require("util"),Bj=`"%s" is not a valid algorithm.
|
|
93
93
|
Supported algorithms are:
|
|
94
94
|
"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Xo="secret must be a string or buffer",Ds="key must be a string or a buffer",jj="key must be a string, a buffer or an object",sm=typeof gr.createPublicKey=="function";sm&&(Ds+=" or a KeyObject",Xo+="or a KeyObject");function o1(r){if(!Bs.isBuffer(r)&&typeof r!="string"&&(!sm||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw kr(Ds)}function a1(r){if(!Bs.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw kr(jj)}function Fj(r){if(!Bs.isBuffer(r)){if(typeof r=="string")return r;if(!sm||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw kr(Xo)}}function om(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function c1(r){r=r.toString();var e=4-r.length%4;if(e!==4)for(var t=0;t<e;++t)r+="=";return r.replace(/\-/g,"+").replace(/_/g,"/")}function kr(r){var e=[].slice.call(arguments,1),t=i1.format.bind(i1,r).apply(null,e);return new TypeError(t)}function $j(r){return Bs.isBuffer(r)||typeof r=="string"}function Jo(r){return $j(r)||(r=JSON.stringify(r)),r}function l1(r){return function(t,n){Fj(n),t=Jo(t);var i=gr.createHmac("sha"+r,n),s=(i.update(t),i.digest("base64"));return om(s)}}var im,Hj="timingSafeEqual"in gr?function(e,t){return e.byteLength!==t.byteLength?!1:gr.timingSafeEqual(e,t)}:function(e,t){return im||(im=n1()),im(e,t)};function Uj(r){return function(t,n,i){var s=l1(r)(t,i);return Hj(Bs.from(n),Bs.from(s))}}function u1(r){return function(t,n){a1(n),t=Jo(t);var i=gr.createSign("RSA-SHA"+r),s=(i.update(t),i.sign(n,"base64"));return om(s)}}function p1(r){return function(t,n,i){o1(i),t=Jo(t),n=c1(n);var s=gr.createVerify("RSA-SHA"+r);return s.update(t),s.verify(i,n,"base64")}}function qj(r){return function(t,n){a1(n),t=Jo(t);var i=gr.createSign("RSA-SHA"+r),s=(i.update(t),i.sign({key:n,padding:gr.constants.RSA_PKCS1_PSS_PADDING,saltLength:gr.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return om(s)}}function Wj(r){return function(t,n,i){o1(i),t=Jo(t),n=c1(n);var s=gr.createVerify("RSA-SHA"+r);return s.update(t),s.verify({key:i,padding:gr.constants.RSA_PKCS1_PSS_PADDING,saltLength:gr.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function Gj(r){var e=u1(r);return function(){var n=e.apply(null,arguments);return n=s1.derToJose(n,"ES"+r),n}}function zj(r){var e=p1(r);return function(n,i,s){i=s1.joseToDer(i,"ES"+r).toString("base64");var o=e(n,i,s);return o}}function Vj(){return function(){return""}}function Kj(){return function(e,t){return t===""}}f1.exports=function(e){var t={hs:l1,rs:u1,ps:qj,es:Gj,none:Vj},n={hs:Uj,rs:p1,ps:Wj,es:zj,none:Kj},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw kr(Bj,e);var s=(i[1]||i[3]).toLowerCase(),o=i[2];return{sign:t[s](o),verify:n[s](o)}}});var cm=O((GG,d1)=>{var Yj=require("buffer").Buffer;d1.exports=function(e){return typeof e=="string"?e:typeof e=="number"||Yj.isBuffer(e)?e.toString():JSON.stringify(e)}});var y1=O((zG,x1)=>{var Xj=Ls().Buffer,h1=tm(),Jj=am(),Qj=require("stream"),m1=cm(),lm=require("util");function g1(r,e){return Xj.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Zj(r,e,t){t=t||"utf8";var n=g1(m1(r),"binary"),i=g1(m1(e),t);return lm.format("%s.%s",n,i)}function v1(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,i=r.encoding,s=Jj(e.alg),o=Zj(e,t,i),a=s.sign(o,n);return lm.format("%s.%s",o,a)}function iu(r){var e=r.secret;if(e=e??r.privateKey,e=e??r.key,/^hs/i.test(r.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new h1(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new h1(r.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}lm.inherits(iu,Qj);iu.prototype.sign=function(){try{var e=v1({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(t){this.readable=!1,this.emit("error",t),this.emit("close")}};iu.sign=v1;x1.exports=iu});var k1=O((VG,R1)=>{var b1=Ls().Buffer,_1=tm(),eF=am(),tF=require("stream"),w1=cm(),rF=require("util"),nF=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function iF(r){return Object.prototype.toString.call(r)==="[object Object]"}function sF(r){if(iF(r))return r;try{return JSON.parse(r)}catch{return}}function S1(r){var e=r.split(".",1)[0];return sF(b1.from(e,"base64").toString("binary"))}function oF(r){return r.split(".",2).join(".")}function E1(r){return r.split(".")[2]}function aF(r,e){e=e||"utf8";var t=r.split(".")[1];return b1.from(t,"base64").toString(e)}function T1(r){return nF.test(r)&&!!S1(r)}function C1(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=w1(r);var i=E1(r),s=oF(r),o=eF(e);return o.verify(s,i,t)}function A1(r,e){if(e=e||{},r=w1(r),!T1(r))return null;var t=S1(r);if(!t)return null;var n=aF(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:E1(r)}}function js(r){r=r||{};var e=r.secret;if(e=e??r.publicKey,e=e??r.key,/^hs/i.test(r.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new _1(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new _1(r.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}rF.inherits(js,tF);js.prototype.verify=function(){try{var e=C1(this.signature.buffer,this.algorithm,this.key.buffer),t=A1(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};js.decode=A1;js.isValid=T1;js.verify=C1;R1.exports=js});var P1=O(zn=>{var O1=y1(),su=k1(),cF=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];zn.ALGORITHMS=cF;zn.sign=O1.sign;zn.verify=su.verify;zn.decode=su.decode;zn.isValid=su.isValid;zn.createSign=function(e){return new O1(e)};zn.createVerify=function(e){return new su(e)}});var ou=O((YG,M1)=>{"use strict";var um={};um.supportedContentEncodings={AES_GCM:"aesgcm",AES_128_GCM:"aes128gcm"};um.supportedUrgency={VERY_LOW:"very-low",LOW:"low",NORMAL:"normal",HIGH:"high"};M1.exports=um});var pm=O((XG,I1)=>{"use strict";function lF(r){return/^[A-Za-z0-9\-_]+$/.test(r)}I1.exports={validate:lF}});var dm=O((JG,H1)=>{"use strict";var uF=require("crypto"),pF=qE(),fF=P1(),{URL:L1}=require("url"),N1=ou(),D1=pm(),dF=720*60,hF=1440*60,mF=pF.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).objid().optional(),this.key("publicKey").explicit(1).bitstr().optional())});function gF(r){return mF.encode({version:1,privateKey:r,parameters:[1,2,840,10045,3,1,7]},"pem",{label:"EC PRIVATE KEY"})}function vF(){let r=uF.createECDH("prime256v1");r.generateKeys();let e=r.getPublicKey(),t=r.getPrivateKey();if(t.length<32){let n=Buffer.alloc(32-t.length);n.fill(0),t=Buffer.concat([n,t])}if(e.length<65){let n=Buffer.alloc(65-e.length);n.fill(0),e=Buffer.concat([n,e])}return{publicKey:e.toString("base64url"),privateKey:t.toString("base64url")}}function B1(r){if(!r)throw new Error("No subject set in vapidDetails.subject.");if(typeof r!="string"||r.length===0)throw new Error("The subject value must be a string containing an https: URL or mailto: address. "+r);let e=null;try{e=new L1(r)}catch{throw new Error("Vapid subject is not a valid URL. "+r)}if(!["https:","mailto:"].includes(e.protocol))throw new Error("Vapid subject is not an https: or mailto: URL. "+r);e.hostname==="localhost"&&console.warn("Vapid subject points to a localhost web URI, which is unsupported by Apple's push notification server and will result in a BadJwtToken error when sending notifications.")}function j1(r){if(!r)throw new Error("No key set vapidDetails.publicKey");if(typeof r!="string")throw new Error("Vapid public key is must be a URL safe Base 64 encoded string.");if(!D1.validate(r))throw new Error('Vapid public key must be a URL safe Base 64 (without "=")');if(r=Buffer.from(r,"base64url"),r.length!==65)throw new Error("Vapid public key should be 65 bytes long when decoded.")}function F1(r){if(!r)throw new Error("No key set in vapidDetails.privateKey");if(typeof r!="string")throw new Error("Vapid private key must be a URL safe Base 64 encoded string.");if(!D1.validate(r))throw new Error('Vapid private key must be a URL safe Base 64 (without "=")');if(r=Buffer.from(r,"base64url"),r.length!==32)throw new Error("Vapid private key should be 32 bytes long when decoded.")}function fm(r){let e=new Date;return e.setSeconds(e.getSeconds()+r),Math.floor(e.getTime()/1e3)}function $1(r){if(!Number.isInteger(r))throw new Error("`expiration` value must be a number");if(r<0)throw new Error("`expiration` must be a positive integer");let e=fm(hF);if(r>=e)throw new Error("`expiration` value is greater than maximum of 24 hours")}function xF(r,e,t,n,i,s){if(!r)throw new Error("No audience could be generated for VAPID.");if(typeof r!="string"||r.length===0)throw new Error("The audience value must be a string containing the origin of a push service. "+r);try{new L1(r)}catch{throw new Error("VAPID audience is not a url. "+r)}B1(e),j1(t),F1(n),n=Buffer.from(n,"base64url"),s?$1(s):s=fm(dF);let o={typ:"JWT",alg:"ES256"},a={aud:r,exp:s,sub:e},c=fF.sign({header:o,payload:a,privateKey:gF(n)});if(i===N1.supportedContentEncodings.AES_128_GCM)return{Authorization:"vapid t="+c+", k="+t};if(i===N1.supportedContentEncodings.AES_GCM)return{Authorization:"WebPush "+c,"Crypto-Key":"p256ecdsa="+t};throw new Error("Unsupported encoding type specified.")}H1.exports={generateVAPIDKeys:vF,getFutureExpirationTimestamp:fm,getVapidHeaders:xF,validateSubject:B1,validatePublicKey:j1,validatePrivateKey:F1,validateExpiration:$1}});var Q1=O((QG,J1)=>{"use strict";var cu=require("crypto"),q1="aes-128-gcm",lu={aes128gcm:1,aesgcm:2},yi=16,Wr=16,yF=12,W1=32,Qo="encrypt",Zo="decrypt",de;process.env.ECE_KEYLOG==="1"?de=function(r,e){return console.warn(r+" ["+e.length+"]: "+e.toString("base64url")),e}:de=function(r,e){return e};function au(r){return typeof r=="string"?Buffer.from(r,"base64url"):r}function G1(r,e){var t=cu.createHmac("sha256",r);return t.update(e),t.digest()}function z1(r,e){return de("salt",r),de("ikm",e),de("extract",G1(r,e))}function hm(r,e,t){de("prk",r),de("info",e);var n=Buffer.alloc(0),i=Buffer.alloc(0);e=Buffer.from(e,"ascii");for(var s=0,o=Buffer.alloc(1);n.length<t;)o.writeUIntBE(++s,0,1),i=G1(r,Buffer.concat([i,e,o])),n=Buffer.concat([n,i]);return de("expand",n.slice(0,t))}function V1(r,e,t,n){return hm(z1(r,e),t,n)}function mm(r,e){var t=Buffer.concat([Buffer.from("Content-Encoding: "+r+"\0","ascii"),e]);return de("info "+r,t),t}function U1(r){var e=Buffer.concat([Buffer.alloc(2),r]);return e.writeUIntBE(r.length,0,2),e}function _F(r,e){var t=r.privateKey,n,i;if(e===Qo)n=t.getPublicKey(),i=r.dh;else if(e===Zo)n=r.dh,i=t.getPublicKey();else throw new Error("Unknown mode only "+Qo+" and "+Zo+" supported");return{secret:t.computeSecret(r.dh),context:Buffer.concat([Buffer.from(r.keylabel,"ascii"),Buffer.from([0]),U1(i),U1(n)])}}function bF(r,e){var t={secret:null,context:Buffer.alloc(0)};if(r.key){if(t.secret=r.key,t.secret.length!==Wr)throw new Error("An explicit key must be "+Wr+" bytes")}else r.dh?t=_F(r,e):typeof r.keyid!==void 0&&(t.secret=r.keymap[r.keyid]);if(!t.secret)throw new Error("Unable to determine key");return de("secret",t.secret),de("context",t.context),r.authSecret&&(t.secret=V1(r.authSecret,t.secret,mm("auth",Buffer.alloc(0)),W1),de("authsecret",t.secret)),t}function wF(r,e){if(!r.authSecret)throw new Error("No authentication secret for webpush");de("authsecret",r.authSecret);var t,n,i;if(e===Qo)n=r.privateKey.getPublicKey(),t=i=r.dh;else if(e===Zo)t=n=r.keyid,i=r.privateKey.getPublicKey();else throw new Error("Unknown mode only "+Qo+" and "+Zo+" supported");return de("remote pubkey",t),de("sender pubkey",n),de("receiver pubkey",i),de("secret dh",V1(r.authSecret,r.privateKey.computeSecret(t),Buffer.concat([Buffer.from("WebPush: info\0"),i,n]),W1))}function SF(r,e,t){if(t&&!MF(t))throw new Error("Callback is not a function");if(r.key){if(r.key.length!==Wr)throw new Error("An explicit key must be "+Wr+" bytes");return de("secret key",r.key)}if(!r.privateKey){if(t)var n=t(r.keyid);else var n=r.keymap&&r.keymap[r.keyid];if(!n)throw new Error('No saved key (keyid: "'+r.keyid+'")');return n}return wF(r,e)}function K1(r,e,t){if(!r.salt)throw new Error("must include a salt parameter for "+r.version);var n,i,s;if(r.version==="aesgcm"){var o=bF(r,e,t);n=mm("aesgcm",o.context),i=mm("nonce",o.context),s=o.secret}else if(r.version==="aes128gcm")n=Buffer.from("Content-Encoding: aes128gcm\0"),i=Buffer.from("Content-Encoding: nonce\0"),s=SF(r,e,t);else throw new Error("Unable to set context for mode "+r.version);var a=z1(r.salt,s),c={key:hm(a,n,Wr),nonce:hm(a,i,yF)};return de("key",c.key),de("nonce base",c.nonce),c}function Y1(r){var e={};e.version=r.version||"aes128gcm",e.rs=parseInt(r.rs,10),isNaN(e.rs)&&(e.rs=4096);var t=lu[e.version];if(e.version==="aes128gcm"&&(t+=yi),e.rs<=t)throw new Error("The rs parameter has to be greater than "+t);if(r.salt&&(e.salt=au(r.salt),e.salt.length!==Wr))throw new Error("The salt parameter must be "+Wr+" bytes");return e.keyid=r.keyid,r.key?e.key=au(r.key):(e.privateKey=r.privateKey,e.privateKey||(e.keymap=r.keymap),e.version!=="aes128gcm"&&(e.keylabel=r.keylabel||"P-256"),r.dh&&(e.dh=au(r.dh))),r.authSecret&&(e.authSecret=au(r.authSecret)),e}function X1(r,e){var t=Buffer.from(r),n=t.readUIntBE(t.length-6,6),i=((n^e)&16777215)+((n/16777216^e/16777216)&16777215)*16777216;return t.writeUIntBE(i,t.length-6,6),de("nonce"+e,t),t}function EF(r,e){var t=r.readUIntBE(20,1);return e.salt=r.slice(0,Wr),e.rs=r.readUIntBE(Wr,4),e.keyid=r.slice(21,21+t),21+t}function TF(r,e){var t=lu[e],n=r.readUIntBE(0,t);if(n+t>r.length)throw new Error("padding exceeds block size");de("padding",r.slice(0,t+n));var i=Buffer.alloc(n);if(i.fill(0),i.compare(r.slice(t,t+n))!==0)throw new Error("invalid padding");return r.slice(t+n)}function CF(r,e){for(var t=r.length-1;t>=0;){if(r[t]){if(e){if(r[t]!==2)throw new Error("last record needs to start padding with a 2")}else if(r[t]!==1)throw new Error("last record needs to start padding with a 2");return r.slice(0,t)}--t}throw new Error("all zero plaintext")}function AF(r,e,t,n,i){de("decrypt",t);var s=X1(r.nonce,e),o=cu.createDecipheriv(q1,r.key,s);o.setAuthTag(t.slice(t.length-yi));var a=o.update(t.slice(0,t.length-yi));return a=Buffer.concat([a,o.final()]),de("decrypted",a),n.version!=="aes128gcm"?TF(a,n.version):CF(a,i)}function RF(r,e,t){var n=Y1(e);if(n.version==="aes128gcm"){var i=EF(r,n);r=r.slice(i)}var s=K1(n,Zo,t),o=0,a=Buffer.alloc(0),c=n.rs;n.version!=="aes128gcm"&&(c+=yi);for(var u=0;o<r.length;++u){var p=o+c;if(n.version!=="aes128gcm"&&p===r.length)throw new Error("Truncated payload");if(p=Math.min(p,r.length),p-o<=yi)throw new Error("Invalid block: too small at "+u);var f=AF(s,u,r.slice(o,p),n,p>=r.length);a=Buffer.concat([a,f]),o=p}return a}function kF(r,e,t,n,i,s){de("encrypt",t),n=n||0;var o=X1(r.nonce,e),a=cu.createCipheriv(q1,r.key,o),c=[],u=lu[i.version],p=Buffer.alloc(n+u);if(p.fill(0),i.version!=="aes128gcm"){if(p.writeUIntBE(n,0,u),de("padding",p),c.push(a.update(p)),c.push(a.update(t)),!s&&p.length+t.length<i.rs)throw new Error("Unable to pad to record size")}else c.push(a.update(t)),p.writeUIntBE(s?2:1,0,1),de("padding",p),c.push(a.update(p));a.final();var f=a.getAuthTag();if(f.length!==yi)throw new Error("invalid tag generated");return c.push(f),de("encrypted",Buffer.concat(c))}function OF(r){var e=Buffer.alloc(5),t=Buffer.from(r.keyid||[]);if(t.length>255)throw new Error("keyid is too large");return e.writeUIntBE(r.rs,0,4),e.writeUIntBE(t.length,4,1),Buffer.concat([r.salt,e,t])}function PF(r,e,t){if(!Buffer.isBuffer(r))throw new Error("buffer argument must be a Buffer");var n=Y1(e);n.salt||(n.salt=cu.randomBytes(Wr));var i;n.version==="aes128gcm"?(n.privateKey&&!n.keyid&&(n.keyid=n.privateKey.getPublicKey()),i=OF(n)):i=Buffer.alloc(0);var s=K1(n,Qo,t),o=0,a=lu[n.version],c=a;n.version==="aes128gcm"&&(c+=yi);for(var u=isNaN(parseInt(e.pad,10))?0:parseInt(e.pad,10),p=0,f=!1;!f;){var m=Math.min(n.rs-c-1,u);n.version!=="aes128gcm"&&(m=Math.min((1<<a*8)-1,m)),u>0&&m===0&&++m,u-=m;var y=o+n.rs-c-m;n.version!=="aes128gcm"?f=y>r.length:f=y>=r.length,f=f&&u<=0;var _=kF(s,p,r.slice(o,y),m,n,f);i=Buffer.concat([i,_]),o=y,++p}return i}function MF(r){return typeof r=="function"}J1.exports={decrypt:RF,encrypt:PF}});var gm=O((ZG,eT)=>{"use strict";var Z1=require("crypto"),IF=Q1(),NF=function(r,e,t,n){if(!r)throw new Error("No user public key provided for encryption.");if(typeof r!="string")throw new Error("The subscription p256dh value must be a string.");if(Buffer.from(r,"base64url").length!==65)throw new Error("The subscription p256dh value should be 65 bytes long.");if(!e)throw new Error("No user auth provided for encryption.");if(typeof e!="string")throw new Error("The subscription auth key must be a string.");if(Buffer.from(e,"base64url").length<16)throw new Error("The subscription auth key should be at least 16 bytes long");if(typeof t!="string"&&!Buffer.isBuffer(t))throw new Error("Payload must be either a string or a Node Buffer.");(typeof t=="string"||t instanceof String)&&(t=Buffer.from(t));let i=Z1.createECDH("prime256v1"),s=i.generateKeys(),o=Z1.randomBytes(16).toString("base64url"),a=IF.encrypt(t,{version:n,dh:r,privateKey:i,salt:o,authSecret:e});return{localPublicKey:s,salt:o,cipherText:a}};eT.exports={encrypt:NF}});var vm=O((ez,rT)=>{"use strict";function tT(r,e,t,n,i){Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=r,this.statusCode=e,this.headers=t,this.body=n,this.endpoint=i}require("util").inherits(tT,Error);rT.exports=tT});var sT=O(Ft=>{"use strict";var LF=Ft&&Ft.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),DF=Ft&&Ft.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),nT=Ft&&Ft.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&LF(e,r,t);return DF(e,r),e};Object.defineProperty(Ft,"__esModule",{value:!0});Ft.req=Ft.json=Ft.toBuffer=void 0;var BF=nT(require("http")),jF=nT(require("https"));async function iT(r){let e=0,t=[];for await(let n of r)e+=n.length,t.push(n);return Buffer.concat(t,e)}Ft.toBuffer=iT;async function FF(r){let t=(await iT(r)).toString("utf8");try{return JSON.parse(t)}catch(n){let i=n;throw i.message+=` (input: ${t})`,i}}Ft.json=FF;function $F(r,e={}){let n=((typeof r=="string"?r:r.href).startsWith("https:")?jF:BF).request(r,e),i=new Promise((s,o)=>{n.once("response",s).once("error",o).end()});return n.then=i.then.bind(i),n}Ft.req=$F});var lT=O(Qt=>{"use strict";var aT=Qt&&Qt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),HF=Qt&&Qt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),cT=Qt&&Qt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&aT(e,r,t);return HF(e,r),e},UF=Qt&&Qt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&aT(e,r,t)};Object.defineProperty(Qt,"__esModule",{value:!0});Qt.Agent=void 0;var qF=cT(require("net")),oT=cT(require("http")),WF=require("https");UF(sT(),Qt);var Gr=Symbol("AgentBaseInternalState"),xm=class extends oT.Agent{constructor(e){super(e),this[Gr]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
|
|
@@ -111,7 +111,7 @@ WantedBy=default.target
|
|
|
111
111
|
`),!0}catch(e){return console.error("[DaemonClient] Send error:",e),!1}}function bl(r,e=5e3){return new Promise((t,n)=>{let i=gB();r.requestId=i;let s=setTimeout(()=>{xs.delete(i),n(new Error("Request timeout"))},e);xs.set(i,{resolve:t,reject:n,timer:s}),th(r)||(clearTimeout(s),xs.delete(i),n(new Error("Not connected to daemon")))})}function vB(r){let{type:e,requestId:t,...n}=r;if(t&&xs.has(t)){let{resolve:i,timer:s}=xs.get(t);clearTimeout(s),xs.delete(t),i({type:e,...n});return}switch(e){case"output":vl("output",{sessionId:n.sessionId,data:Buffer.from(n.data,"base64")});break;case"sessionClosed":vl("sessionClosed",n.sessionId);break;case"pong":break;default:console.log("[DaemonClient] Unknown message:",e)}}function xl(){return new Promise(r=>{let e=yl.default.connect(Lo),t=setTimeout(()=>{e.destroy(),r(!1)},1e3);e.on("connect",()=>{clearTimeout(t),e.destroy(),r(!0)}),e.on("error",()=>{if(clearTimeout(t),process.platform!=="win32"&&ae.default.existsSync(Lo))try{ae.default.unlinkSync(Lo)}catch{}r(!1)})})}function xB(){ae.default.existsSync(fn)||ae.default.mkdirSync(fn,{recursive:!0});let r=ae.default.existsSync(aw)?aw:ae.default.existsSync(cw)?cw:null;if(!r)return console.error("[DaemonClient] \u274C Daemon script not found"),null;let e=hB(r);return e||{script:r,cwd:eh}}async function yB(){if(!ae.default.existsSync(fn))try{ae.default.mkdirSync(fn,{recursive:!0})}catch(a){return console.error("[DaemonClient] Failed to create socket directory:",a.message),!1}let r=xB();if(!r)return!1;let{script:e,cwd:t}=r,n=pe.default.join(fn,"logs");try{ae.default.mkdirSync(n,{recursive:!0})}catch{}let i=pe.default.join(n,"daemon.log"),s;try{s=ae.default.openSync(i,"w")}catch(a){console.error("[DaemonClient] Failed to open log file:",a.message),s="ignore"}if((0,uw.spawn)("node",[e],{detached:!0,stdio:["ignore",s,s],cwd:t}).unref(),typeof s=="number")try{ae.default.closeSync(s)}catch{}for(let a=0;a<20;a++)if(await new Promise(c=>setTimeout(c,100)),await xl())return!0;console.error("[DaemonClient] \u274C Failed to start daemon");try{let a=ae.default.readFileSync(i,"utf8");a.trim()&&(console.error("[DaemonClient] Daemon log:"),console.error(a))}catch{}return!1}function _B(){return new Promise(r=>{let e=yl.default.connect(Lo),t="",n=s=>{try{e.destroy()}catch{}r(s)},i=setTimeout(()=>n(null),2e3);e.on("connect",()=>e.write(JSON.stringify({type:"ping",requestId:-1})+`
|
|
112
112
|
`)),e.on("data",s=>{t+=s.toString();let o=t.indexOf(`
|
|
113
113
|
`);if(o!==-1){clearTimeout(i);try{let a=JSON.parse(t.slice(0,o));n(a.version||"unknown")}catch{n(null)}}}),e.on("error",()=>{clearTimeout(i),n(null)})})}async function bB(){try{let r=pe.default.join(fn,"pids","ptyDaemon.pid"),e=parseInt(ae.default.readFileSync(r,"utf8").trim(),10);Number.isFinite(e)&&e>0&&process.kill(e,"SIGTERM")}catch{}for(let r=0;r<20;r++){if(!await xl())return;await new Promise(e=>setTimeout(e,100))}}async function dw(){if(!(vs||Fn)){Fn=!0;try{if(await xl()){let r=await _B();r!=="18"&&(console.log(`[DaemonClient] Daemon v${r} != v${"18"}, restarting`),await bB())}return!await xl()&&!await yB()?(console.error("[DaemonClient] \u274C Failed to start daemon"),Fn=!1,!1):new Promise(r=>{let e=setTimeout(()=>{console.error("[DaemonClient] \u274C Connection timeout after 5s"),$r&&$r.destroy(),Fn=!1,r(!1)},5e3);$r=yl.default.connect(Lo),$r.on("connect",()=>{clearTimeout(e),vs=!0,Fn=!1,vl("connected"),r(!0)}),$r.on("data",t=>{Zd+=t.toString();let n=Zd.split(`
|
|
114
|
-
`);Zd=n.pop()||"";for(let i of n)if(i.trim())try{vB(JSON.parse(i))}catch{console.error("[DaemonClient] Invalid message:",i)}}),$r.on("close",()=>{vs=!1,$r=null,vl("disconnected"),setTimeout(()=>{!vs&&!Fn&&dw()},2e3)}),$r.on("error",t=>{clearTimeout(e),console.error("[DaemonClient] \u274C Connection error:",t.message),console.error("[DaemonClient] Error code:",t.code),Fn=!1,r(!1)})})}catch(r){return console.error("[DaemonClient] \u274C Connect error:",r),Fn=!1,!1}}}async function hw(){return dw()}function Cr(){return vs}async function wl(){return(await bl({type:"listSessions"})).sessions||[]}async function rh(r,e=80,t=24,n=null,i=`session-${Date.now()}`,s=null){return await bl({type:"createSession",sessionId:i,name:r,cols:e,rows:t,shellId:n,cwd:s})}async function mw(r){return await bl({type:"joinSession",sessionId:r})}function nh(r,e){return th({type:"input",sessionId:r,data:e})}function gw(r,e,t){return th({type:"resize",sessionId:r,cols:e,rows:t})}async function di(r){return await bl({type:"deleteSession",sessionId:r})}Li();var xw=require("child_process");bt();var wB={darwin:()=>({cmd:"caffeinate",args:["-u","-t",String(Z.displayWake.macDurationSec)]}),linux:()=>({cmd:"xset",args:["dpms","force","on"]}),win32:()=>({cmd:"powershell.exe",args:["-NonInteractive","-NoProfile","-WindowStyle","Hidden","-Command",`Add-Type -Name K -Namespace W -MemberDefinition '[System.Runtime.InteropServices.DllImport("kernel32")]public static extern uint SetThreadExecutionState(uint e);'; [void][W.K]::SetThreadExecutionState(0x80000003)`]})},vw=0;function yw(){let r=Z.displayWake;if(!r?.enabled)return;let e=Date.now();if(e-vw<r.throttleMs)return;vw=e;let t=wB[process.platform];if(t)try{let{cmd:n,args:i}=t(),s=(0,xw.spawn)(n,i,{detached:!0,stdio:"ignore",windowsHide:!0});s.on("error",()=>{}),s.unref()}catch{}}var PS=Rn("remote"),gn=null;function ZB(){return process.env.CODESPACES==="true"||process.env.GITPOD_WORKSPACE_ID||process.platform==="linux"&&!process.env.DISPLAY}async function DS(){if(gn!==null)return gn;if(ZB())return gn=!1,PS.info("\u2705 Remote desktop not available (headless environment)"),gn;try{let r=await import("@hurdlegroup/robotjs");(r.default||r).getScreenSize(),gn=!0}catch{gn=!1,PS.info("\u2705 Remote desktop not available (no display or robotjs not installed)")}return gn}function BS(){return gn===!0}var mi=null,jS=null,FS=null,$S=null,HS=null,US=null,qS=null,mn=null,MS=null,IS=null,NS=null,LS=null;async function ej(){if(mi)return!0;try{let r=await import("@hurdlegroup/robotjs");mi=r.default||r;let{TileManager:e}=await Promise.resolve().then(()=>(bS(),_S)),{ResourceManager:t}=await Promise.resolve().then(()=>(SS(),wS)),{ScreenUpdateHelper:n}=await Promise.resolve().then(()=>(TS(),ES)),{MouseHandler:i}=await Promise.resolve().then(()=>(AS(),CS)),{KeyboardHandler:s}=await Promise.resolve().then(()=>(OS(),kS)),{ScreenHandler:o}=await Promise.resolve().then(()=>(Xd(),nw));return jS=e,FS=t,$S=n,HS=i,US=s,qS=o,mi.setMouseDelay(2),mi.setKeyboardDelay(2),!0}catch(r){return console.error("\u274C Failed to load remote modules:",r.message),!1}}async function WS(r,e){if(!gn){r.emit("remote:unavailable");return}if(!await ej()){r.emit("remote:unavailable");return}mn||(mn=new FS,MS=new $S(mn),IS=new HS(mi,mn),NS=new US(mi,mn),LS=new qS(mn,MS),mn.startResourceMonitoring());let n=r.handshake.auth?.apiKey,i=new jS(mi);mn.addClient(r.id,{tileManager:i,screenInterval:null,authenticated:!0,apiKey:n});let s=r.data.protocol;if(!s){r.emit("remote:unavailable");return}r.data.remoteAttached=!0;let o=a=>(...c)=>(yw(),a(...c));IS.setupMouseHandlers(r,o),NS.setupKeyboardHandlers(r,o),LS.setupScreenHandlers(r,o,s),r.on("disconnect",()=>{let a=()=>{mn.removeClient(r.id),s.close(),dl(s)},c=s._adapters?.get("rtc");if(!c?.ready)return a();c.on("stateChange",u=>{u===dt.closed&&a()})}),r.emit("remote:ready")}Un();var qn=X(require("fs"),1),Ph=X(require("path"),1),jl=0,Ko=null,tj=6e4,rj={name:"9Remote",postCreateCommand:"npm install -g 9remote@latest",postAttachCommand:"9remote start",forwardPorts:[2208],portsAttributes:{2208:{label:"9Remote Server",onAutoForward:"notify"}}};function vn(){return process.env.CODESPACES==="true"}function GS(){return vn()?{isCodespaces:!0,codespaceName:process.env.CODESPACE_NAME||"unknown",workspacePath:process.env.CODESPACE_VSCODE_FOLDER||process.cwd()}:null}function zS(){jl++,vn()&&jl===1&&nj()}function VS(){jl--,vn()&&jl===0&&ij()}function nj(){Ko||(Ko=setInterval(()=>{process.memoryUsage()},tj))}function ij(){Ko&&(console.log("\u23F8\uFE0F Stopping Codespaces heartbeat"),clearInterval(Ko),Ko=null)}function KS(r){return Ph.default.join(r,".devcontainer","devcontainer.json")}function YS(r){try{let e=KS(r);if(!qn.default.existsSync(e))return{enabled:!1,exists:!1};let t=JSON.parse(qn.default.readFileSync(e,"utf8"));return{enabled:t.postAttachCommand==="9remote start"||t.postAttachCommand==="9remote",exists:!0}}catch{return{enabled:!1,exists:!1,error:"Failed to read config"}}}function XS(r,e){try{let t=Ph.default.join(r,".devcontainer"),n=KS(r);qn.default.existsSync(t)||qn.default.mkdirSync(t,{recursive:!0});let i={...rj};if(qn.default.existsSync(n))try{i={...JSON.parse(qn.default.readFileSync(n,"utf8"))}}catch{}return e?(i.postAttachCommand="9remote start",i.postCreateCommand||(i.postCreateCommand="npm install -g 9remote@latest")):delete i.postAttachCommand,qn.default.writeFileSync(n,JSON.stringify(i,null,2)),{success:!0,enabled:e}}catch(t){return{success:!1,error:t.message}}}var Fl=X(require("os"),1),ke=X(require("fs"),1),Wn=X(require("path"),1);vt();var Cs=oe.BUFFERS,$l=Wn.default.join(oe.STATE,"sessions.json"),Hl=Wn.default.join(oe.STATE,"terminalGroups.json"),Ul="/tmp/9remote-uploads";ke.default.existsSync(Ul)||ke.default.mkdirSync(Ul,{recursive:!0});function Mh(){return process.platform==="win32"?process.env.COMSPEC||"powershell.exe":process.env.SHELL||"/bin/zsh"}function Ih(r){return r?"/workspaces":Fl.default.homedir()}function Nh(){let r=Fl.default.homedir(),e=Fl.default.userInfo().username,t=Mh(),n={...process.env};if(Object.assign(n,{HOME:r,USER:e,LOGNAME:e,SHELL:t,TERM:"xterm-256color",COLORTERM:"truecolor",LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8",LC_CTYPE:"en_US.UTF-8",PWD:r,OLDPWD:r,TMPDIR:n.TMPDIR||(process.platform==="win32"?n.TEMP||n.TMP:"/tmp"),__CF_USER_TEXT_ENCODING:n.__CF_USER_TEXT_ENCODING,XPC_FLAGS:n.XPC_FLAGS,XPC_SERVICE_NAME:n.XPC_SERVICE_NAME,SSH_AUTH_SOCK:n.SSH_AUTH_SOCK,TERM_PROGRAM:"9Remote",TERM_PROGRAM_VERSION:"1.0.0",ITERM_SESSION_ID:`9remote-${Date.now()}`,SHLVL:"1"}),t.includes("bash")){let i=n.PROMPT_COMMAND||"";n.PROMPT_COMMAND=`printf "\\e]7;file://%s\\a" "\${HOSTNAME}\${PWD}"${i?`; ${i}`:""}`}return n}function JS(){ke.default.existsSync(Cs)||ke.default.mkdirSync(Cs,{recursive:!0})}function Lh(r,e,t){if(t==="buffer"){JS();try{ke.default.writeFileSync(Wn.default.join(Cs,`${r}.buf`),e.join(""),"utf8")}catch(n){console.log(`\u26A0\uFE0F Failed to save buffer for ${r}:`,n.message)}}}function QS(r,e){if(e!=="buffer")return null;let t=Wn.default.join(Cs,`${r}.buf`);try{if(ke.default.existsSync(t))return ke.default.readFileSync(t,"utf8")}catch(n){console.log(`\u26A0\uFE0F Failed to load buffer for ${r}:`,n.message)}return null}function ql(r){let e=Wn.default.join(Cs,`${r}.buf`);try{ke.default.existsSync(e)&&ke.default.unlinkSync(e)}catch{}}function ZS(){JS();try{return ke.default.readdirSync(Cs).filter(r=>r.endsWith(".buf")).map(r=>r.replace(".buf",""))}catch{return[]}}function Dh(){try{if(ke.default.existsSync($l))return JSON.parse(ke.default.readFileSync($l,"utf8"))}catch(r){console.log("\u26A0\uFE0F Failed to load session metadata:",r.message)}return{}}function xn(r){try{let e={};for(let[n,i]of r)e[n]={name:i.name,createdAt:i.createdAt,shellId:i.shellId,cwd:i.cwd};let t=Wn.default.dirname($l);ke.default.existsSync(t)||ke.default.mkdirSync(t,{recursive:!0}),ke.default.writeFileSync($l,JSON.stringify(e,null,2),"utf8")}catch(e){console.log("\u26A0\uFE0F Failed to save session metadata:",e.message)}}function eE(){try{if(ke.default.existsSync(Hl)){let r=JSON.parse(ke.default.readFileSync(Hl,"utf8"));return{groups:r.groups||[],sessionGroups:r.sessionGroups||{}}}}catch(r){console.log("\u26A0\uFE0F Failed to load groups:",r.message)}return{groups:[],sessionGroups:{}}}function tE(r,e){try{let t=Wn.default.dirname(Hl);ke.default.existsSync(t)||ke.default.mkdirSync(t,{recursive:!0});let n={groups:Array.from(r.values()),sessionGroups:e};ke.default.writeFileSync(Hl,JSON.stringify(n,null,2),"utf8")}catch(t){console.log("\u26A0\uFE0F Failed to save groups:",t.message)}}var Bh=X(require("node-pty"),1);var rE=2*1024*1024,sj=256*1024,gi="daemon";function nE(r,e,t,n,i){let s=null;r.onData(o=>{t.buffer.push(o),t.buffer.reduce((c,u)=>c+u.length,0)>rE&&(t.buffer=[t.buffer.join("").slice(-rE)]),wt(n,"output",{sessionId:e,data:Buffer.from(o,"utf-8")}),gi==="buffer"&&(s&&clearTimeout(s),s=setTimeout(()=>Lh(e,t.buffer,gi),2e3))}),r.onExit(({exitCode:o})=>{console.log(`PTY exited: sessionId=${e}, code=${o}`),gi==="buffer"&&t.buffer.length>0&&Lh(e,t.buffer,gi),i.delete(e),ql(e),wt(n,"sessionClosed",e)})}function iE(r,e,t,n,i){let s=()=>tE(n,i);r.on("getSessions",o=>{let a=[];for(let[c,u]of t)a.push({id:c,name:u.name,createdAt:u.createdAt,restored:u.restored||!1,shellId:u.shellId,shellLabel:u.shellLabel,groupId:i[c]||null});o(a)}),r.on("getShells",o=>{o({platform:process.platform,shells:sw()})}),r.on("getGroups",o=>{o(Array.from(n.values()))}),r.on("createGroup",({name:o},a)=>{let c=`group-${Date.now()}`,u={id:c,name:o||"Group",createdAt:Date.now()};n.set(c,u),s(),wt(e,"groupsChanged"),a({success:!0,group:u})}),r.on("renameGroup",({groupId:o,name:a},c)=>{let u=n.get(o);if(!u)return c({success:!1,error:"Group not found"});u.name=a,s(),wt(e,"groupsChanged"),c({success:!0})}),r.on("deleteGroup",async({groupId:o},a)=>{if(!n.delete(o))return a({success:!1,error:"Group not found"});let c=Object.keys(i).filter(u=>i[u]===o);for(let u of c){let p=t.get(u);if(p){if(p.daemon&&Cr())try{await di(u)}catch{}else p.pty&&(p.pty.kill(),ql(u));t.delete(u),wt(e,"sessionClosed",u)}delete i[u]}s(),wt(e,"groupsChanged"),a({success:!0})}),r.on("moveSession",({sessionId:o,groupId:a},c)=>{a&&n.has(a)?i[o]=a:delete i[o],s(),wt(e,"groupsChanged"),c({success:!0})}),r.on("createSession",async({name:o,shellId:a,groupId:c},u)=>{let p=`session-${Date.now()}`,f=ow(a),m=Nh();m.NINE_REMOTE_SESSION_ID=p;let y=Ih(vn());try{let _=o||`${f.label} ${t.size+1}`;if(gi==="daemon"&&Cr()){let P=await rh(_,80,24,a,p,y);P.success?(t.set(P.sessionId,{daemon:!0,name:_,createdAt:Date.now(),cwd:P.cwd,shellId:P.shellId,shellLabel:P.shellLabel}),c&&n.has(c)&&(i[P.sessionId]=c,s()),xn(t),u({success:!0,sessionId:P.sessionId,shellLabel:P.shellLabel})):u({success:!1,error:P.error});return}let S=Bh.default.spawn(f.path,f.args,{name:"xterm-256color",cols:80,rows:24,cwd:y,env:m,useConpty:!1}),A={pty:S,name:_,createdAt:Date.now(),buffer:[],cwd:y,shellId:f.id,shellLabel:f.label};nE(S,p,A,e,t),t.set(p,A),c&&n.has(c)&&(i[p]=c,s()),u({success:!0,sessionId:p,shellLabel:f.label})}catch(_){console.error("Failed to create session:",_),u({success:!1,error:_.message})}}),r.on("joinSession",async(o,a)=>{let c=t.get(o);if(!c)return a({success:!1,error:"Session not found"});if(c.daemon&&Cr()){try{if(c.needsRespawn){let p=await rh(c.name,80,24,c.shellId,o,c.cwd);if(!p.success)return a({success:!1,error:p.error});delete c.needsRespawn,c.cwd=p.cwd,c.shellLabel=p.shellLabel,xn(t)}let u=await mw(o);u.cwd&&u.cwd!==c.cwd&&(c.cwd=u.cwd,xn(t)),a({success:u.success,name:c.name,cwd:u.cwd||c.cwd,error:u.error})}catch(u){a({success:!1,error:u.message})}return}if(c.needsRestore&&gi==="buffer")try{let u=Mh(),p=process.platform==="win32"?[]:["-l"],f=Ih(vn()),m=Bh.default.spawn(u,p,{name:"xterm-256color",cols:80,rows:24,cwd:f,env:Nh(),useConpty:!1});c.pty=m,c.needsRestore=!1,c.cwd=f;let y=QS(o,gi);y&&(c.buffer=[y]),nE(m,o,c,e,t),console.log(`\u2705 Restored PTY session: ${o}`)}catch(u){return console.error("Failed to restore session:",u),a({success:!1,error:"Failed to restore session"})}c.buffer?.length>0&&r.emit("output",{sessionId:o,data:Buffer.from(c.buffer.join("").slice(-sj),"utf-8")}),a({success:!0,name:c.name,cwd:c.cwd})}),r.on("deleteSession",async(o,a)=>{let c=t.get(o);if(!c)return a({success:!1,error:"Session not found"});if(c.daemon&&Cr()){try{await di(o),t.delete(o),i[o]&&(delete i[o],s()),xn(t),a({success:!0})}catch(u){a({success:!1,error:u.message})}return}c.pty&&c.pty.kill(),t.delete(o),i[o]&&(delete i[o],s()),ql(o),wt(e,"sessionClosed",o),xn(t),a({success:!0})}),r.on("renameSession",async({sessionId:o,name:a},c)=>{let u=t.get(o);if(!u)return c({success:!1,error:"Session not found"});u.name=a,wt(e,"session-renamed",{sessionId:o,name:a}),xn(t),c({success:!0})})}var sE=X(require("fs"),1),oE=X(require("path"),1);function aE(r,e){r.on("input",({sessionId:t,data:n})=>{if(!t)return;let i=e.get(t);if(i){if(i.daemon&&Cr())return nh(t,n);i.pty&&i.pty.write(Buffer.isBuffer(n)?n.toString("utf-8"):n)}}),r.on("resize",({sessionId:t,cols:n,rows:i})=>{if(!t)return;let s=e.get(t);if(s){if(s.daemon&&Cr())return gw(t,n,i);if(s.pty)try{s.pty.resize(n,i)}catch(o){console.log(`Resize failed for ${t}: ${o.message}`)}}}),r.on("upload-file",({sessionId:t,filename:n,size:i,content:s})=>{if(!t)return;let o=e.get(t);if(o)try{let a=n.replace(/[^a-zA-Z0-9._-]/g,"_"),c=oE.default.join(Ul,`${Date.now()}_${a}`);sE.default.writeFileSync(c,Buffer.from(s,"base64")),console.log(`\u{1F4CE} File uploaded: ${c} (${i} bytes)`),o.daemon&&Cr()?nh(t,c):o.pty&&o.pty.write(c)}catch(a){console.error("File upload error:",a),r.emit("output",{sessionId:t,data:Buffer.from(`\r
|
|
114
|
+
`);Zd=n.pop()||"";for(let i of n)if(i.trim())try{vB(JSON.parse(i))}catch{console.error("[DaemonClient] Invalid message:",i)}}),$r.on("close",()=>{vs=!1,$r=null,vl("disconnected"),setTimeout(()=>{!vs&&!Fn&&dw()},2e3)}),$r.on("error",t=>{clearTimeout(e),console.error("[DaemonClient] \u274C Connection error:",t.message),console.error("[DaemonClient] Error code:",t.code),Fn=!1,r(!1)})})}catch(r){return console.error("[DaemonClient] \u274C Connect error:",r),Fn=!1,!1}}}async function hw(){return dw()}function Cr(){return vs}async function wl(){return(await bl({type:"listSessions"})).sessions||[]}async function rh(r,e=80,t=24,n=null,i=`session-${Date.now()}`,s=null){return await bl({type:"createSession",sessionId:i,name:r,cols:e,rows:t,shellId:n,cwd:s})}async function mw(r){return await bl({type:"joinSession",sessionId:r})}function nh(r,e){return th({type:"input",sessionId:r,data:e})}function gw(r,e,t){return th({type:"resize",sessionId:r,cols:e,rows:t})}async function di(r){return await bl({type:"deleteSession",sessionId:r})}Li();var xw=require("child_process");bt();var wB={darwin:()=>({cmd:"caffeinate",args:["-u","-t",String(Z.displayWake.macDurationSec)]}),linux:()=>({cmd:"xset",args:["dpms","force","on"]}),win32:()=>({cmd:"powershell.exe",args:["-NonInteractive","-NoProfile","-WindowStyle","Hidden","-Command",`Add-Type -Name K -Namespace W -MemberDefinition '[System.Runtime.InteropServices.DllImport("kernel32")]public static extern uint SetThreadExecutionState(uint e);'; [void][W.K]::SetThreadExecutionState(0x80000003)`]})},vw=0;function yw(){let r=Z.displayWake;if(!r?.enabled)return;let e=Date.now();if(e-vw<r.throttleMs)return;vw=e;let t=wB[process.platform];if(t)try{let{cmd:n,args:i}=t(),s=(0,xw.spawn)(n,i,{detached:!0,stdio:"ignore",windowsHide:!0});s.on("error",()=>{}),s.unref()}catch{}}var PS=Rn("remote"),gn=null;function ZB(){return process.env.CODESPACES==="true"||process.env.GITPOD_WORKSPACE_ID||process.platform==="linux"&&!process.env.DISPLAY}async function DS(){if(gn!==null)return gn;if(ZB())return gn=!1,PS.info("\u2705 Remote desktop not available (headless environment)"),gn;try{let r=await import("@hurdlegroup/robotjs");(r.default||r).getScreenSize(),gn=!0}catch{gn=!1,PS.info("\u2705 Remote desktop not available (no display or robotjs not installed)")}return gn}function BS(){return gn===!0}var mi=null,jS=null,FS=null,$S=null,HS=null,US=null,qS=null,mn=null,MS=null,IS=null,NS=null,LS=null;async function ej(){if(mi)return!0;try{let r=await import("@hurdlegroup/robotjs");mi=r.default||r;let{TileManager:e}=await Promise.resolve().then(()=>(bS(),_S)),{ResourceManager:t}=await Promise.resolve().then(()=>(SS(),wS)),{ScreenUpdateHelper:n}=await Promise.resolve().then(()=>(TS(),ES)),{MouseHandler:i}=await Promise.resolve().then(()=>(AS(),CS)),{KeyboardHandler:s}=await Promise.resolve().then(()=>(OS(),kS)),{ScreenHandler:o}=await Promise.resolve().then(()=>(Xd(),nw));return jS=e,FS=t,$S=n,HS=i,US=s,qS=o,mi.setMouseDelay(2),mi.setKeyboardDelay(2),!0}catch(r){return console.error("\u274C Failed to load remote modules:",r.message),!1}}async function WS(r,e){if(!gn){r.emit("remote:unavailable");return}if(!await ej()){r.emit("remote:unavailable");return}mn||(mn=new FS,MS=new $S(mn),IS=new HS(mi,mn),NS=new US(mi,mn),LS=new qS(mn,MS),mn.startResourceMonitoring());let n=r.handshake.auth?.apiKey,i=new jS(mi);mn.addClient(r.id,{tileManager:i,screenInterval:null,authenticated:!0,apiKey:n});let s=r.data.protocol;if(!s){r.emit("remote:unavailable");return}r.data.remoteAttached=!0;let o=a=>(...c)=>(yw(),a(...c));IS.setupMouseHandlers(r,o),NS.setupKeyboardHandlers(r,o),LS.setupScreenHandlers(r,o,s),r.on("disconnect",()=>{let a=()=>{mn.removeClient(r.id),s.close(),dl(s)},c=s._adapters?.get("rtc");if(!c?.ready)return a();c.on("stateChange",u=>{u===dt.closed&&a()})}),r.emit("remote:ready")}Un();var qn=X(require("fs"),1),Ph=X(require("path"),1),jl=0,Ko=null,tj=6e4,rj={name:"9Remote",postCreateCommand:"npm install -g 9remote@latest",postAttachCommand:"9remote start",forwardPorts:[2208],portsAttributes:{2208:{label:"9Remote Server",onAutoForward:"notify"}}};function vn(){return process.env.CODESPACES==="true"}function GS(){return vn()?{isCodespaces:!0,codespaceName:process.env.CODESPACE_NAME||"unknown",workspacePath:process.env.CODESPACE_VSCODE_FOLDER||process.cwd()}:null}function zS(){jl++,vn()&&jl===1&&nj()}function VS(){jl--,vn()&&jl===0&&ij()}function nj(){Ko||(Ko=setInterval(()=>{process.memoryUsage()},tj))}function ij(){Ko&&(console.log("\u23F8\uFE0F Stopping Codespaces heartbeat"),clearInterval(Ko),Ko=null)}function KS(r){return Ph.default.join(r,".devcontainer","devcontainer.json")}function YS(r){try{let e=KS(r);if(!qn.default.existsSync(e))return{enabled:!1,exists:!1};let t=JSON.parse(qn.default.readFileSync(e,"utf8"));return{enabled:t.postAttachCommand==="9remote start"||t.postAttachCommand==="9remote",exists:!0}}catch{return{enabled:!1,exists:!1,error:"Failed to read config"}}}function XS(r,e){try{let t=Ph.default.join(r,".devcontainer"),n=KS(r);qn.default.existsSync(t)||qn.default.mkdirSync(t,{recursive:!0});let i={...rj};if(qn.default.existsSync(n))try{i={...JSON.parse(qn.default.readFileSync(n,"utf8"))}}catch{}return e?(i.postAttachCommand="9remote start",i.postCreateCommand||(i.postCreateCommand="npm install -g 9remote@latest")):delete i.postAttachCommand,qn.default.writeFileSync(n,JSON.stringify(i,null,2)),{success:!0,enabled:e}}catch(t){return{success:!1,error:t.message}}}var Fl=X(require("os"),1),ke=X(require("fs"),1),Wn=X(require("path"),1);vt();var Cs=oe.BUFFERS,$l=Wn.default.join(oe.STATE,"sessions.json"),Hl=Wn.default.join(oe.STATE,"terminalGroups.json"),Ul="/tmp/9remote-uploads";ke.default.existsSync(Ul)||ke.default.mkdirSync(Ul,{recursive:!0});function Mh(){return process.platform==="win32"?process.env.COMSPEC||"powershell.exe":process.env.SHELL||"/bin/zsh"}function Ih(r){return r?"/workspaces":Fl.default.homedir()}function Nh(){let r=Fl.default.homedir(),e=Fl.default.userInfo().username,t=Mh(),n={...process.env};if(delete n.PORT,Object.assign(n,{HOME:r,USER:e,LOGNAME:e,SHELL:t,TERM:"xterm-256color",COLORTERM:"truecolor",LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8",LC_CTYPE:"en_US.UTF-8",PWD:r,OLDPWD:r,TMPDIR:n.TMPDIR||(process.platform==="win32"?n.TEMP||n.TMP:"/tmp"),__CF_USER_TEXT_ENCODING:n.__CF_USER_TEXT_ENCODING,XPC_FLAGS:n.XPC_FLAGS,XPC_SERVICE_NAME:n.XPC_SERVICE_NAME,SSH_AUTH_SOCK:n.SSH_AUTH_SOCK,TERM_PROGRAM:"9Remote",TERM_PROGRAM_VERSION:"1.0.0",ITERM_SESSION_ID:`9remote-${Date.now()}`,SHLVL:"1"}),t.includes("bash")){let i=n.PROMPT_COMMAND||"";n.PROMPT_COMMAND=`printf "\\e]7;file://%s\\a" "\${HOSTNAME}\${PWD}"${i?`; ${i}`:""}`}return n}function JS(){ke.default.existsSync(Cs)||ke.default.mkdirSync(Cs,{recursive:!0})}function Lh(r,e,t){if(t==="buffer"){JS();try{ke.default.writeFileSync(Wn.default.join(Cs,`${r}.buf`),e.join(""),"utf8")}catch(n){console.log(`\u26A0\uFE0F Failed to save buffer for ${r}:`,n.message)}}}function QS(r,e){if(e!=="buffer")return null;let t=Wn.default.join(Cs,`${r}.buf`);try{if(ke.default.existsSync(t))return ke.default.readFileSync(t,"utf8")}catch(n){console.log(`\u26A0\uFE0F Failed to load buffer for ${r}:`,n.message)}return null}function ql(r){let e=Wn.default.join(Cs,`${r}.buf`);try{ke.default.existsSync(e)&&ke.default.unlinkSync(e)}catch{}}function ZS(){JS();try{return ke.default.readdirSync(Cs).filter(r=>r.endsWith(".buf")).map(r=>r.replace(".buf",""))}catch{return[]}}function Dh(){try{if(ke.default.existsSync($l))return JSON.parse(ke.default.readFileSync($l,"utf8"))}catch(r){console.log("\u26A0\uFE0F Failed to load session metadata:",r.message)}return{}}function xn(r){try{let e={};for(let[n,i]of r)e[n]={name:i.name,createdAt:i.createdAt,shellId:i.shellId,cwd:i.cwd};let t=Wn.default.dirname($l);ke.default.existsSync(t)||ke.default.mkdirSync(t,{recursive:!0}),ke.default.writeFileSync($l,JSON.stringify(e,null,2),"utf8")}catch(e){console.log("\u26A0\uFE0F Failed to save session metadata:",e.message)}}function eE(){try{if(ke.default.existsSync(Hl)){let r=JSON.parse(ke.default.readFileSync(Hl,"utf8"));return{groups:r.groups||[],sessionGroups:r.sessionGroups||{}}}}catch(r){console.log("\u26A0\uFE0F Failed to load groups:",r.message)}return{groups:[],sessionGroups:{}}}function tE(r,e){try{let t=Wn.default.dirname(Hl);ke.default.existsSync(t)||ke.default.mkdirSync(t,{recursive:!0});let n={groups:Array.from(r.values()),sessionGroups:e};ke.default.writeFileSync(Hl,JSON.stringify(n,null,2),"utf8")}catch(t){console.log("\u26A0\uFE0F Failed to save groups:",t.message)}}var Bh=X(require("node-pty"),1);var rE=2*1024*1024,sj=256*1024,gi="daemon";function nE(r,e,t,n,i){let s=null;r.onData(o=>{t.buffer.push(o),t.buffer.reduce((c,u)=>c+u.length,0)>rE&&(t.buffer=[t.buffer.join("").slice(-rE)]),wt(n,"output",{sessionId:e,data:Buffer.from(o,"utf-8")}),gi==="buffer"&&(s&&clearTimeout(s),s=setTimeout(()=>Lh(e,t.buffer,gi),2e3))}),r.onExit(({exitCode:o})=>{console.log(`PTY exited: sessionId=${e}, code=${o}`),gi==="buffer"&&t.buffer.length>0&&Lh(e,t.buffer,gi),i.delete(e),ql(e),wt(n,"sessionClosed",e)})}function iE(r,e,t,n,i){let s=()=>tE(n,i);r.on("getSessions",o=>{let a=[];for(let[c,u]of t)a.push({id:c,name:u.name,createdAt:u.createdAt,restored:u.restored||!1,shellId:u.shellId,shellLabel:u.shellLabel,groupId:i[c]||null});o(a)}),r.on("getShells",o=>{o({platform:process.platform,shells:sw()})}),r.on("getGroups",o=>{o(Array.from(n.values()))}),r.on("createGroup",({name:o},a)=>{let c=`group-${Date.now()}`,u={id:c,name:o||"Group",createdAt:Date.now()};n.set(c,u),s(),wt(e,"groupsChanged"),a({success:!0,group:u})}),r.on("renameGroup",({groupId:o,name:a},c)=>{let u=n.get(o);if(!u)return c({success:!1,error:"Group not found"});u.name=a,s(),wt(e,"groupsChanged"),c({success:!0})}),r.on("deleteGroup",async({groupId:o},a)=>{if(!n.delete(o))return a({success:!1,error:"Group not found"});let c=Object.keys(i).filter(u=>i[u]===o);for(let u of c){let p=t.get(u);if(p){if(p.daemon&&Cr())try{await di(u)}catch{}else p.pty&&(p.pty.kill(),ql(u));t.delete(u),wt(e,"sessionClosed",u)}delete i[u]}s(),wt(e,"groupsChanged"),a({success:!0})}),r.on("moveSession",({sessionId:o,groupId:a},c)=>{a&&n.has(a)?i[o]=a:delete i[o],s(),wt(e,"groupsChanged"),c({success:!0})}),r.on("createSession",async({name:o,shellId:a,groupId:c},u)=>{let p=`session-${Date.now()}`,f=ow(a),m=Nh();m.NINE_REMOTE_SESSION_ID=p;let y=Ih(vn());try{let _=o||`${f.label} ${t.size+1}`;if(gi==="daemon"&&Cr()){let P=await rh(_,80,24,a,p,y);P.success?(t.set(P.sessionId,{daemon:!0,name:_,createdAt:Date.now(),cwd:P.cwd,shellId:P.shellId,shellLabel:P.shellLabel}),c&&n.has(c)&&(i[P.sessionId]=c,s()),xn(t),u({success:!0,sessionId:P.sessionId,shellLabel:P.shellLabel})):u({success:!1,error:P.error});return}let S=Bh.default.spawn(f.path,f.args,{name:"xterm-256color",cols:80,rows:24,cwd:y,env:m,useConpty:!1}),A={pty:S,name:_,createdAt:Date.now(),buffer:[],cwd:y,shellId:f.id,shellLabel:f.label};nE(S,p,A,e,t),t.set(p,A),c&&n.has(c)&&(i[p]=c,s()),u({success:!0,sessionId:p,shellLabel:f.label})}catch(_){console.error("Failed to create session:",_),u({success:!1,error:_.message})}}),r.on("joinSession",async(o,a)=>{let c=t.get(o);if(!c)return a({success:!1,error:"Session not found"});if(c.daemon&&Cr()){try{if(c.needsRespawn){let p=await rh(c.name,80,24,c.shellId,o,c.cwd);if(!p.success)return a({success:!1,error:p.error});delete c.needsRespawn,c.cwd=p.cwd,c.shellLabel=p.shellLabel,xn(t)}let u=await mw(o);u.cwd&&u.cwd!==c.cwd&&(c.cwd=u.cwd,xn(t)),a({success:u.success,name:c.name,cwd:u.cwd||c.cwd,error:u.error})}catch(u){a({success:!1,error:u.message})}return}if(c.needsRestore&&gi==="buffer")try{let u=Mh(),p=process.platform==="win32"?[]:["-l"],f=Ih(vn()),m=Bh.default.spawn(u,p,{name:"xterm-256color",cols:80,rows:24,cwd:f,env:Nh(),useConpty:!1});c.pty=m,c.needsRestore=!1,c.cwd=f;let y=QS(o,gi);y&&(c.buffer=[y]),nE(m,o,c,e,t),console.log(`\u2705 Restored PTY session: ${o}`)}catch(u){return console.error("Failed to restore session:",u),a({success:!1,error:"Failed to restore session"})}c.buffer?.length>0&&r.emit("output",{sessionId:o,data:Buffer.from(c.buffer.join("").slice(-sj),"utf-8")}),a({success:!0,name:c.name,cwd:c.cwd})}),r.on("deleteSession",async(o,a)=>{let c=t.get(o);if(!c)return a({success:!1,error:"Session not found"});if(c.daemon&&Cr()){try{await di(o),t.delete(o),i[o]&&(delete i[o],s()),xn(t),a({success:!0})}catch(u){a({success:!1,error:u.message})}return}c.pty&&c.pty.kill(),t.delete(o),i[o]&&(delete i[o],s()),ql(o),wt(e,"sessionClosed",o),xn(t),a({success:!0})}),r.on("renameSession",async({sessionId:o,name:a},c)=>{let u=t.get(o);if(!u)return c({success:!1,error:"Session not found"});u.name=a,wt(e,"session-renamed",{sessionId:o,name:a}),xn(t),c({success:!0})})}var sE=X(require("fs"),1),oE=X(require("path"),1);function aE(r,e){r.on("input",({sessionId:t,data:n})=>{if(!t)return;let i=e.get(t);if(i){if(i.daemon&&Cr())return nh(t,n);i.pty&&i.pty.write(Buffer.isBuffer(n)?n.toString("utf-8"):n)}}),r.on("resize",({sessionId:t,cols:n,rows:i})=>{if(!t)return;let s=e.get(t);if(s){if(s.daemon&&Cr())return gw(t,n,i);if(s.pty)try{s.pty.resize(n,i)}catch(o){console.log(`Resize failed for ${t}: ${o.message}`)}}}),r.on("upload-file",({sessionId:t,filename:n,size:i,content:s})=>{if(!t)return;let o=e.get(t);if(o)try{let a=n.replace(/[^a-zA-Z0-9._-]/g,"_"),c=oE.default.join(Ul,`${Date.now()}_${a}`);sE.default.writeFileSync(c,Buffer.from(s,"base64")),console.log(`\u{1F4CE} File uploaded: ${c} (${i} bytes)`),o.daemon&&Cr()?nh(t,c):o.pty&&o.pty.write(c)}catch(a){console.error("File upload error:",a),r.emit("output",{sessionId:t,data:Buffer.from(`\r
|
|
115
115
|
Error uploading file: ${a.message}\r
|
|
116
116
|
`,"utf-8")})}})}var Or=X(require("fs"),1),na=X(require("path"),1),hu=X(ET(),1);vt();Un();var mu=na.default.join(oe.CONFIG,"vapid.json"),gu=na.default.join(oe.CONFIG,"push-subscriptions.json"),lz=1800*1e3,Et=[];function l3(){try{if(Or.default.existsSync(mu))return JSON.parse(Or.default.readFileSync(mu,"utf8"))}catch{}return null}function u3(r){let e=na.default.dirname(mu);Or.default.existsSync(e)||Or.default.mkdirSync(e,{recursive:!0}),Or.default.writeFileSync(mu,JSON.stringify(r,null,2),"utf8")}function p3(){let r=l3();if(!r){let e=hu.default.generateVAPIDKeys();r={publicKey:e.publicKey,privateKey:e.privateKey},u3(r)}return hu.default.setVapidDetails("mailto:admin@9remote.cc",r.publicKey,r.privateKey),r}function f3(){try{Or.default.existsSync(gu)&&(Et=JSON.parse(Or.default.readFileSync(gu,"utf8")))}catch{Et=[]}}function ia(){try{let r=na.default.dirname(gu);Or.default.existsSync(r)||Or.default.mkdirSync(r,{recursive:!0}),Or.default.writeFileSync(gu,JSON.stringify(Et,null,2),"utf8")}catch(r){Te(`Failed to save push subscriptions: ${r.message}`)}}function _i(r){return r.type==="expo"?r.token:r.endpoint}function TT(r,e){let t=_i(r),n=Et.find(i=>_i(i)===t);Et=Et.filter(i=>_i(i)!==t),Et.push({...r,socketId:e,lastConnectedAt:Date.now(),hidden:n?.hidden??!1}),ia()}function CT(r,e){for(let t of Et)t.socketId===r&&(t.hidden=!!e)}function AT(){let r=Et.reduce((e,t)=>(e?.lastConnectedAt??0)>=(t?.lastConnectedAt??0)?e:t,null);return r?r.disconnectedAt!=null||!!r.hidden:!1}function RT(r){Et=Et.filter(e=>_i(e)!==r),ia()}function kT(r){for(let e of Et)e.socketId===r&&(e.disconnectedAt=Date.now());ia()}function OT(r,e){for(let t of Et)_i(t)===e&&(t.socketId=r,t.disconnectedAt=null,t.lastConnectedAt=Date.now());ia()}async function d3(r,e,t){let n={to:r.token,sound:"default",title:t.type==="stop"?`${e} \u2705`:`${e} \u{1F514}`,body:t.type==="stop"?`${e} completed the task`:`${e} needs your input`,data:{url:"/workspace",type:t.type}},s=await(await fetch("https://exp.host/--/api/v2/push/send",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(n)})).json();if(s.data?.status==="error")throw new Error(s.data.message);Te(`Expo push sent to ${r.token.slice(0,30)}...`)}async function PT(r){let e=Dv[r.tool]||"AI",t=Et.reduce((i,s)=>(i?.lastConnectedAt??0)>=(s?.lastConnectedAt??0)?i:s,null);if(!t)return;let n=_i(t);try{if(t.type==="expo")await d3(t,e,r);else{let i=JSON.stringify({title:r.type==="stop"?`${e} \u2705`:`${e} \u{1F514}`,body:r.type==="stop"?`${e} completed the task`:`${e} needs your input`,data:{url:"/workspace",type:r.type}});await hu.default.sendNotification({endpoint:t.endpoint,keys:t.keys},i),Te(`WebPush sent to ${t.endpoint.slice(0,50)}...`)}}catch(i){Te(`Push failed: ${i.statusCode||i.message}`),(i.statusCode===410||i.statusCode===404||i.message?.includes("DeviceNotRegistered"))&&(Et=Et.filter(o=>_i(o)!==n),ia())}}var h3=p3();f3();function MT(){return h3.publicKey}var bm={};function IT(r,e){bm[r]=e}function vu(r){delete bm[r]}function NT(){return{...bm}}ys();function LT(r){r.on("getNotificationState",()=>{r.emit("notificationState",NT())}),r.on("requestUpdate",()=>$n("update")),r.on("clearNotification",e=>{e&&(vu(e),r.broadcast.emit("notificationCleared",e))}),r.on("getVapidKey",e=>e(MT())),r.on("pushSubscribe",e=>{let t=e?.type==="expo"?e.token:e?.endpoint;t&&(OT(r.id,t),TT(e,r.id))}),r.on("pushUnsubscribe",e=>{e&&RT(e)}),r.on("visibilityChange",e=>CT(r.id,e)),r.on("getAutoStartStatus",e=>{if(!vn())return e({success:!1,error:"Not in Codespaces"});let t=process.env.CODESPACE_VSCODE_FOLDER||process.cwd();e({success:!0,...YS(t)})}),r.on("setAutoStart",({enabled:e},t)=>{if(!vn())return t({success:!1,error:"Not in Codespaces"});let n=process.env.CODESPACE_VSCODE_FOLDER||process.cwd();t(XS(n,e))})}var zr=X(require("os"),1),ht=X(require("fs"),1),$t=X(require("path"),1);vt();var BT=`http://localhost:${Ha}/api/notify`,jT="nineRemoteNotify",m3=$t.default.join(oe.STATE,"claudeEnvBackup.json"),_n={claude:()=>$t.default.join(zr.default.homedir(),".claude","settings.json"),codex:()=>$t.default.join(zr.default.homedir(),".codex","config.toml"),gemini:()=>$t.default.join(zr.default.homedir(),".gemini","settings.json"),opencode:()=>$t.default.join(zr.default.homedir(),".config","opencode","plugin",`${jT}.js`)},g3={claude:()=>$t.default.join(zr.default.homedir(),".claude"),codex:()=>$t.default.join(zr.default.homedir(),".codex"),gemini:()=>$t.default.join(zr.default.homedir(),".gemini"),opencode:()=>[$t.default.join(zr.default.homedir(),".config","opencode"),$t.default.join(zr.default.homedir(),".opencode")]},sa=(r,e)=>`command -v curl >/dev/null 2>&1 && curl -s --connect-timeout 1 --max-time 2 "${BT}?type=${r}&sessionId=$NINE_REMOTE_SESSION_ID&tool=${e}" > /dev/null 2>&1 & true`;function oa(r){try{if(ht.default.existsSync(r))return JSON.parse(ht.default.readFileSync(r,"utf8"))}catch{}return{}}function xu(r,e){let t=$t.default.dirname(r);ht.default.existsSync(t)||ht.default.mkdirSync(t,{recursive:!0}),ht.default.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function FT(r){let e={},t=r.env||{};for(let n of Object.keys(oo))e[n]=t[n]??null;xu(m3,e),r.env={...t,...oo}}function v3(){let r=_n.claude(),e=oa(r),t=sa("stop","claude"),n=sa("notification","claude");return e.hooks={...e.hooks||{},Stop:[{matcher:"",hooks:[{type:"command",command:t}]}],Notification:[{matcher:"permission_prompt|idle_prompt",hooks:[{type:"command",command:n}]}]},FT(e),xu(r,e),{success:!0}}var x3=/# 9Remote notification\nnotify\s*=.*\n?/g,y3="# 9Remote-saved: ";function _3(r){let e=r.search(/^\[/m);return e===-1?[r,""]:[r.slice(0,e),r.slice(e)]}var DT=/^notify\s*=\s*(\[[^\n]*\])\s*$/m;function b3(){let r=_n.codex(),e=$t.default.dirname(r);ht.default.existsSync(e)||ht.default.mkdirSync(e,{recursive:!0});let t=ht.default.existsSync(r)?ht.default.readFileSync(r,"utf8"):"";t=t.replace(x3,"");let[n,i]=_3(t),s="",o=n.match(DT);if(o){try{let u=JSON.parse(o[1]);Array.isArray(u)&&u.length&&(s=` ; exec ${u.map(p=>`'${String(p).replace(/'/g,"'\\''")}'`).join(" ")} "$@"`)}catch{}n=n.replace(DT,`${y3}$&`)}let a=`${sa("stop","codex")}${s}`,c=`# 9Remote notification
|
|
117
117
|
notify = ["bash", "-c", ${JSON.stringify(a)}, "9remote"]
|
|
@@ -131,7 +131,7 @@ export const ${jT} = async () => ({
|
|
|
131
131
|
else if (event.type === "permission.asked") post("notification");
|
|
132
132
|
},
|
|
133
133
|
});
|
|
134
|
-
`}function E3(){let r=_n.opencode(),e=$t.default.dirname(r);return ht.default.existsSync(e)||ht.default.mkdirSync(e,{recursive:!0}),ht.default.writeFileSync(r,S3(),"utf8"),{success:!0}}function T3(r){switch(r){case"claude":{let e=oa(_n.claude());return!!(e.hooks?.Stop||e.hooks?.Notification)}case"codex":{let e=_n.codex();return ht.default.existsSync(e)&&ht.default.readFileSync(e,"utf8").includes("# 9Remote notification")}case"gemini":{let e=oa(_n.gemini());return!!(e.hooks?.AfterAgent||e.hooks?.Notification)}case"opencode":return ht.default.existsSync(_n.opencode());default:return!1}}function C3(r){let e=g3[r]?.();return e?(Array.isArray(e)?e:[e]).some(n=>ht.default.existsSync(n)):!1}var A3={claude:v3,codex:b3,gemini:w3,opencode:E3};var R3=Lv;function k3(r){return A3[r]?.()||{success:!1,error:"Unknown tool"}}function $T(){let r={};for(let e of R3)if(!(!C3(e)||T3(e)))try{r[e]=k3(e).success}catch{r[e]=!1}return r}function HT(){let r=_n.claude(),e=oa(r);if(!e.hooks?.Stop&&!e.hooks?.Notification)return;let t=e.env||{};Object.keys(oo).some(i=>t[i]!==oo[i])&&(FT(e),xu(r,e))}var Nz=(0,qT.dirname)((0,WT.fileURLToPath)(__importMetaUrl)),Lz=no.rgb(230,138,110),wm="daemon",O3="2.0.
|
|
134
|
+
`}function E3(){let r=_n.opencode(),e=$t.default.dirname(r);return ht.default.existsSync(e)||ht.default.mkdirSync(e,{recursive:!0}),ht.default.writeFileSync(r,S3(),"utf8"),{success:!0}}function T3(r){switch(r){case"claude":{let e=oa(_n.claude());return!!(e.hooks?.Stop||e.hooks?.Notification)}case"codex":{let e=_n.codex();return ht.default.existsSync(e)&&ht.default.readFileSync(e,"utf8").includes("# 9Remote notification")}case"gemini":{let e=oa(_n.gemini());return!!(e.hooks?.AfterAgent||e.hooks?.Notification)}case"opencode":return ht.default.existsSync(_n.opencode());default:return!1}}function C3(r){let e=g3[r]?.();return e?(Array.isArray(e)?e:[e]).some(n=>ht.default.existsSync(n)):!1}var A3={claude:v3,codex:b3,gemini:w3,opencode:E3};var R3=Lv;function k3(r){return A3[r]?.()||{success:!1,error:"Unknown tool"}}function $T(){let r={};for(let e of R3)if(!(!C3(e)||T3(e)))try{r[e]=k3(e).success}catch{r[e]=!1}return r}function HT(){let r=_n.claude(),e=oa(r);if(!e.hooks?.Stop&&!e.hooks?.Notification)return;let t=e.env||{};Object.keys(oo).some(i=>t[i]!==oo[i])&&(FT(e),xu(r,e))}var Nz=(0,qT.dirname)((0,WT.fileURLToPath)(__importMetaUrl)),Lz=no.rgb(230,138,110),wm="daemon",O3="2.0.59",Vn=new Map,GT=new Map,zT={};async function UT(){let r=await wl(),e=new Map(r.map(n=>[n.id,n])),t=Dh();for(let n of r)if(!t[n.id])try{await di(n.id)}catch{}Vn.clear();for(let[n,i]of Object.entries(t)){let s=e.get(n);Vn.set(n,{daemon:!0,name:i.name,createdAt:i.createdAt,shellId:i.shellId,cwd:s?.cwd||i.cwd,needsRespawn:!s})}xn(Vn)}async function VT(){let r=eE();for(let n of r.groups)GT.set(n.id,n);Object.assign(zT,r.sessionGroups);try{HT()}catch{}try{$T()}catch{}if(wm==="daemon")if(!await hw())console.error("\u274C Failed to connect to PTY daemon, falling back to buffer mode");else{await UT(),_l("connected",()=>{UT().catch(()=>{})});return}console.log("\u{1F4E6} Buffer persistence mode - scrollback enabled");let e=ZS(),t=Dh();for(let n of e){let i=t[n]||{};Vn.set(n,{pty:null,name:i.name||`Terminal ${Vn.size+1}`,createdAt:i.createdAt||Date.now(),buffer:[],needsRestore:!0}),console.log(`\u{1F504} Found saved session: ${n}`)}e.length>0&&console.log(`\u2705 Found ${e.length} saved session(s)`)}function $s(r,e){wm==="daemon"&&(_l("output",({sessionId:i,data:s})=>wt(r,"output",{sessionId:i,data:s})),_l("sessionClosed",i=>{Vn.delete(i),vu(i),wt(r,"sessionClosed",i),wt(r,"notificationCleared",i)}));let t=()=>({version:O3,remoteAvailable:Es(),daemonMode:wm==="daemon"&&Cr(),platform:process.platform,updateAvailable:Kw(),canSelfUpdate:!0,...GS()}),n=()=>{let i=t();for(let s of r.sockets.sockets.values())s.data?.approved&&s.emit("serverInfo",i)};Jw(n),$s._buildServerInfo=t,$s._emitServerInfo=n}function KT(){$s._emitServerInfo?.()}var YT=null;function XT(r){YT=r}async function JT(r,e,t){zS(),YT?.(),r.emit("serverInfo",$s._buildServerInfo?.()),iE(r,e,Vn,GT,zT),aE(r,Vn),LT(r),BS()&&await WS(r,t).catch(n=>{console.error("\u274C Failed to setup remote handlers:",n.message)}),r.on("disconnect",()=>{kT(r.id),VS()})}var se=X(require("fs"),1),yr=X(require("path"),1),Yr=X(require("os"),1),Ks=require("child_process"),RR=X(yR(),1);var Pg=["node_modules",".git","dist","build",".next","coverage","__pycache__",".cache",".vscode",".idea",".turbo",".vercel",".output","out",".nuxt",".svelte-kit","target","vendor",".gradle",".pytest_cache",".mypy_cache",".tox",".venv","venv","env",".DS_Store",".parcel-cache",".rollup.cache"],Hu=[".png",".jpg",".jpeg",".gif",".webp",".ico",".svg",".bmp",".pdf",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".dylib",".mp3",".mp4",".wav",".avi",".mov",".webm",".woff",".woff2",".ttf",".eot",".otf",".sqlite",".db"];var _R=[".ssh",".aws",".gnupg",".kube",".docker",".cargo",".npmrc",".netrc",".pypirc",".config/gh",".config/gcloud"],bR=["/etc/shadow","/etc/sudoers","/etc/ssh","/root","/private/etc/sudoers"];var wR=X(require("fs"),1),wa=X(require("path"),1),SR=X(require("os"),1);var ER=SR.default.homedir();function Pq(r){if(!r)return null;let e=r.startsWith("~")?r.replace(/^~/,ER):r;try{return wR.default.realpathSync(e)}catch{return wa.default.resolve(e)}}function En(r){let e=Pq(r);if(!e)return!1;for(let t of bR)if(e===t||e.startsWith(t+wa.default.sep))return!0;for(let t of _R){let n=wa.default.join(ER,t);if(e===n||e.startsWith(n+wa.default.sep))return!0}return!1}function Uu(r){return Pg.includes(r)}function Ys(r){return Hu.includes(yr.default.extname(r).toLowerCase())}function Iq(r,e){return r.isDirectory()?"folder":Ys(e)?"binary":"file"}function Sa(r){return r<1024?`${r}B`:r<1024*1024?`${(r/1024).toFixed(1)}KB`:`${(r/(1024*1024)).toFixed(1)}MB`}function kR(r,e,t,n=50){if(!(t.length>=n))try{for(let i of se.default.readdirSync(r)){if(t.length>=n)return;if(i.startsWith(".")||Uu(i))continue;let s=yr.default.join(r,i);try{let o=se.default.statSync(s);o.isDirectory()?kR(s,e,t,n):i.toLowerCase().includes(e.toLowerCase())&&t.push({name:i,path:s,type:Ys(i)?"binary":"file",size:o.size,sizeFormatted:Sa(o.size)})}catch{}}}catch{}}function AR(r){if(!r)return null;let e=r.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"::ANY::").replace(/\*/g,"[^/]*").replace(/::ANY::/g,".*").replace(/\?/g,".");return new RegExp(`^${e}$`)}function OR(r,e,t,n,i,s){if(s.length>=200)return;let o;try{o=se.default.readdirSync(r,{withFileTypes:!0})}catch{return}for(let a of o){if(s.length>=200)return;if(Uu(a.name))continue;let c=yr.default.join(r,a.name),u=yr.default.relative(e,c);if(a.isDirectory()){OR(c,e,t,n,i,s);continue}if(a.isFile()&&!Ys(a.name)&&!(i&&i.test(u))&&!(n&&!n.test(u)))try{if(se.default.statSync(c).size>512e3)continue;let m=se.default.readFileSync(c,"utf-8").split(`
|
|
135
135
|
`),y=[];for(let _=0;_<m.length&&y.length<10;_++){let S=m[_],A=t(S);for(let P of A){if(y.length>=10)break;y.push({line:_+1,column:P.column+1,lineText:S,matchLength:P.length})}}y.length&&s.push({path:c,matches:y})}catch{}}}function PR(r,e,t){let n;try{n=se.default.readdirSync(r,{withFileTypes:!0})}catch{return[]}let i=[];for(let s of n){if(!t&&s.name.startsWith(".")&&s.name!==".env"&&s.name!==".env.example"||Uu(s.name))continue;let o=yr.default.join(r,s.name);if(s.isDirectory()){let a={name:s.name,path:o,type:"folder"};e>0&&(a.children=PR(o,e-1,t)),i.push(a)}else s.isFile()&&i.push({name:s.name,path:o,type:Ys(s.name)?"binary":"file"})}return i.sort((s,o)=>s.type==="folder"&&o.type!=="folder"?-1:s.type!=="folder"&&o.type==="folder"?1:s.name.localeCompare(o.name)),i}function Nq(){if(process.platform!=="win32")return[];try{return(0,Ks.execSync)("wmic logicaldisk get name",{encoding:"utf-8",stdio:["pipe","pipe","pipe"],windowsHide:!0}).split(/\r?\n/).map(e=>e.trim()).filter(e=>/^[A-Z]:$/.test(e)).map(e=>({letter:e[0],path:e+"\\"}))}catch{return"CDEFGHIJ".split("").map(r=>`${r}:\\`).filter(r=>se.default.existsSync(r)).map(r=>({letter:r[0],path:r}))}}function MR(r){r.on("getSystemInfo",t=>{let n=process.platform;t({success:!0,platform:n,isWindows:n==="win32",drives:n==="win32"?Nq():[],homedir:Yr.default.homedir()})}),r.on("getFiles",({dirPath:t,showHidden:n},i)=>{try{let s=t||Yr.default.homedir(),o=s.startsWith("~")?s.replace("~",Yr.default.homedir()):s;if(En(o))return i({success:!1,error:"Access denied"});if(!se.default.existsSync(o))return i({success:!1,error:"Directory not found"});let a=[];for(let c of se.default.readdirSync(o))if(!(!n&&c.startsWith(".")&&c!==".env"&&c!==".env.example")&&!Uu(c))try{let u=yr.default.join(o,c),p=se.default.statSync(u);a.push({name:c,path:u,type:Iq(p,c),size:p.isFile()?p.size:null,sizeFormatted:p.isFile()?Sa(p.size):null,modified:p.mtime.getTime()})}catch{}a.sort((c,u)=>c.type==="folder"&&u.type!=="folder"?-1:c.type!=="folder"&&u.type==="folder"?1:c.name.localeCompare(u.name)),i({success:!0,files:a,currentPath:o,parentPath:yr.default.dirname(o)})}catch(s){i({success:!1,error:s.message})}}),r.on("searchFiles",({workspace:t,query:n},i)=>{try{if(!n||n.length<2)return i({success:!0,files:[]});let s=(t||Yr.default.homedir()).replace(/^~/,Yr.default.homedir());if(!se.default.existsSync(s))return i({success:!1,error:"Workspace not found"});let o=[];kR(s,n,o,50),o.sort((a,c)=>{let u=a.name.toLowerCase()===n.toLowerCase(),p=c.name.toLowerCase()===n.toLowerCase();return u&&!p?-1:!u&&p?1:a.path.length-c.path.length}),i({success:!0,files:o})}catch(s){i({success:!1,error:s.message})}}),r.on("readFile",({filePath:t},n)=>{try{if(En(t))return n({success:!1,error:"Access denied"});if(!se.default.existsSync(t))return n({success:!1,error:"File not found"});let i=se.default.statSync(t);if(i.size>512e3)return n({success:!1,error:`File too large (${Sa(i.size)}). Max ${Sa(512e3)}`});if(Ys(t))return n({success:!1,error:"Cannot open binary file"});n({success:!0,content:se.default.readFileSync(t,"utf-8")})}catch(i){n({success:!1,error:i.message})}}),r.on("readImage",({filePath:t},n)=>{try{if(En(t))return n({success:!1,error:"Access denied"});if(!se.default.existsSync(t))return n({success:!1,error:"File not found"});let i=se.default.statSync(t),s=10*1024*1024;if(i.size>s)return n({success:!1,error:`Image too large (${Sa(i.size)})`});let o=yr.default.extname(t).toLowerCase().slice(1),c={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",bmp:"image/bmp"}[o]||"application/octet-stream",u=se.default.readFileSync(t),p=`data:${c};base64,${u.toString("base64")}`;n({success:!0,dataUrl:p,size:i.size,mime:c})}catch(i){n({success:!1,error:i.message})}}),r.on("writeFile",({filePath:t,content:n},i)=>{try{if(En(t))return i({success:!1,error:"Access denied"});se.default.writeFileSync(t,n,"utf-8"),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),r.on("createItem",({itemPath:t,type:n},i)=>{try{if(En(t))return i({success:!1,error:"Access denied"});if(se.default.existsSync(t))return i({success:!1,error:"Item already exists"});n==="folder"?se.default.mkdirSync(t,{recursive:!0}):se.default.writeFileSync(t,"","utf-8"),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),r.on("deleteItem",({itemPath:t},n)=>{try{if(En(t))return n({success:!1,error:"Access denied"});if(!se.default.existsSync(t))return n({success:!1,error:"Item not found"});se.default.statSync(t).isDirectory()?se.default.rmSync(t,{recursive:!0}):se.default.unlinkSync(t),n({success:!0})}catch(i){n({success:!1,error:i.message})}}),r.on("renameItem",({oldPath:t,newPath:n},i)=>{try{if(En(t)||En(n))return i({success:!1,error:"Access denied"});if(!se.default.existsSync(t))return i({success:!1,error:"Item not found"});if(se.default.existsSync(n))return i({success:!1,error:"Target already exists"});se.default.renameSync(t,n),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),r.on("searchInFiles",({workspace:t,query:n,caseSensitive:i,regex:s,includeGlob:o,excludeGlob:a},c)=>{try{if(!n)return c({success:!0,results:[]});let u=(t||Yr.default.homedir()).replace(/^~/,Yr.default.homedir());if(!se.default.existsSync(u))return c({success:!1,error:"Workspace not found"});let p;if(s){let _;try{_=new RegExp(n,i?"g":"gi")}catch(S){return c({success:!1,error:`Invalid regex: ${S.message}`})}p=S=>{let A=[],P;for(_.lastIndex=0;(P=_.exec(S))!==null;)A.push({column:P.index,length:P[0].length}),P.index===_.lastIndex&&_.lastIndex++;return A}}else{let _=i?n:n.toLowerCase();p=S=>{let A=i?S:S.toLowerCase(),P=[],L=0;for(;(L=A.indexOf(_,L))!==-1;)P.push({column:L,length:_.length}),L+=_.length||1;return P}}let f=AR(o),m=AR(a),y=[];OR(u,u,p,f,m,y),c({success:!0,results:y})}catch(u){c({success:!1,error:u.message})}}),r.on("replaceInFiles",({workspace:t,query:n,replacement:i,caseSensitive:s,regex:o,files:a},c)=>{try{if(!n||!Array.isArray(a)||!a.length)return c({success:!0,replacedCount:0,fileCount:0});let u;if(o){let m;try{m=new RegExp(n,s?"g":"gi")}catch(y){return c({success:!1,error:`Invalid regex: ${y.message}`})}u=y=>{let _=0;return{next:y.replace(m,A=>(_++,i)),count:_}}}else u=m=>{let y=0,_=s?"g":"gi",S=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),A=new RegExp(S,_);return{next:m.replace(A,()=>(y++,i)),count:y}};let p=0,f=0;for(let m of a)try{if(!se.default.existsSync(m)||Ys(m))continue;let y=se.default.statSync(m);if(!y.isFile()||y.size>512e3)continue;let _=se.default.readFileSync(m,"utf-8"),{next:S,count:A}=u(_);A>0&&(se.default.writeFileSync(m,S,"utf-8"),p+=A,f++)}catch{}c({success:!0,replacedCount:p,fileCount:f})}catch(u){c({success:!1,error:u.message})}});let e=new Map;r.on("watchDir",({dirPath:t},n)=>{try{if(!t||!se.default.existsSync(t))return n({success:!1,error:"Directory not found"});if(e.has(t))return n({success:!0});let i=RR.default.watch(t,{depth:0,ignoreInitial:!0,persistent:!0,ignored:o=>Pg.includes(yr.default.basename(o))}),s=o=>a=>r.emit("fileChange",{type:o,path:a});i.on("add",s("add")).on("change",s("change")).on("unlink",s("unlink")).on("addDir",s("addDir")).on("unlinkDir",s("unlinkDir")),e.set(t,i),n({success:!0})}catch(i){n({success:!1,error:i.message})}}),r.on("unwatchDir",({dirPath:t},n)=>{try{let i=e.get(t);i&&(i.close(),e.delete(t)),n({success:!0})}catch(i){n({success:!1,error:i.message})}}),r.once("disconnect",()=>{for(let t of e.values())try{t.close()}catch{}e.clear()}),r.on("revealInOS",({filePath:t},n)=>{try{if(!t)return n({success:!1,error:"No path"});let i=process.platform,s,o;i==="darwin"?(s="open",o=["-R",t]):i==="win32"?(s="explorer",o=[`/select,${t}`]):(s="xdg-open",o=[yr.default.dirname(t)]);let a=(0,Ks.spawn)(s,o,{detached:!0,stdio:"ignore",windowsHide:!0});a.on("error",c=>n({success:!1,error:c.message})),a.unref(),n({success:!0})}catch(i){n({success:!1,error:i.message})}}),r.on("openInTerminal",({dirPath:t},n)=>{try{if(!t||!se.default.existsSync(t))return n({success:!1,error:"Directory not found"});let i=process.platform,s,o,a={detached:!0,stdio:"ignore",windowsHide:!0};i==="darwin"?(s="open",o=["-a","Terminal",t]):i==="win32"?(s="cmd",o=["/C","start","cmd","/K",`cd /d "${t}"`],a.shell=!1):(s="gnome-terminal",o=[`--working-directory=${t}`]);let c=(0,Ks.spawn)(s,o,a);c.on("error",()=>{if(i==="linux"){let u=(0,Ks.spawn)("xterm",["-e",`cd "${t}" && bash`],a);u.on("error",p=>n({success:!1,error:p.message})),u.unref()}else n({success:!1,error:"Failed to open terminal"})}),c.unref(),n({success:!0})}catch(i){n({success:!1,error:i.message})}}),r.on("getFileTree",({dirPath:t,depth:n,showHidden:i},s)=>{try{let o=(t||Yr.default.homedir()).replace(/^~/,Yr.default.homedir());if(!se.default.existsSync(o))return s({success:!1,error:"Directory not found"});let c=PR(o,typeof n=="number"?n:3,!!i);s({success:!0,tree:{name:yr.default.basename(o)||o,path:o,type:"folder",children:c}})}catch(o){s({success:!1,error:o.message})}})}var qt=X(require("fs"),1),Ti=X(require("path"),1),Mr=require("child_process");function Ei(r,e){return new Promise(t=>{let n=(0,Mr.spawn)("git",r,{cwd:e,windowsHide:!0}),i="",s="";n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.on("error",o=>t({code:-1,stdout:i,stderr:o.message})),n.on("close",o=>t({code:o,stdout:i,stderr:s}))})}function IR(r){return Hu.includes(Ti.default.extname(r).toLowerCase())}function NR(r){r.on("gitStatus",({repoPath:e},t)=>{try{let n=(0,Mr.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"],windowsHide:!0}),i={};try{(0,Mr.execSync)("git diff HEAD --numstat",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"],windowsHide:!0}).trim().split(`
|
|
136
136
|
`).filter(Boolean).forEach(a=>{let c=a.split(" ");c.length>=3&&(i[c[2]]={added:c[0]==="-"?0:parseInt(c[0],10)||0,deleted:c[1]==="-"?0:parseInt(c[1],10)||0})})}catch{}let s=[];for(let o of n.trim().split(`
|
|
137
137
|
`).filter(Boolean)){let a=o.match(/^([MADRCU?! ]{1,2})\s+(.+)$/);if(!a)continue;let c=a[1],u=a[2];if(!u)continue;let p;c.includes("?")?p="?":c.includes("A")?p="A":c.includes("D")?p="D":c.includes("M")?p="M":c.includes("R")?p="R":p=c.trim()[0]||"?";let f=i[u]||{added:0,deleted:0};if(p==="?")try{let m=Ti.default.join(e,u);if(qt.default.existsSync(m)&&!IR(u)){let y=qt.default.readFileSync(m,"utf-8");f.added=y.split(`
|
|
@@ -261,7 +261,7 @@ self.addEventListener('fetch', (event) => {
|
|
|
261
261
|
</body>
|
|
262
262
|
</html>
|
|
263
263
|
`);return}e._proxyTargetPort=n,e.url=i+(s||""),r.web(e,t,{target:`http://localhost:${n}`,changeOrigin:!0},o=>{t.writeHead(502),t.end(`Bad Gateway: ${o.message}`)})}var Vk=X(require("http"),1),Kk=X(require("https"),1),Yk=require("child_process"),Xk=require("util"),x4=(0,Xk.promisify)(Yk.exec);async function y4(){let r=process.platform,e=new Set([80,443]);try{let t;if(r==="win32")t="netstat -ano | findstr LISTENING";else{let s="/dev/null";t=`lsof -iTCP -sTCP:LISTEN -P -n 2>${s} || netstat -tlnp 2>${s}`}let{stdout:n}=await x4(t),i=n.split(`
|
|
264
|
-
`);for(let s of i){let o=s.match(/[:\*\]](\d{2,5})(?:\s|$)/g);if(o)for(let a of o){let c=parseInt(a.replace(/[:\*\]\s]/g,""),10);c>0&&c<=65535&&(c===80||c===443||c>=1024)&&e.add(c)}}return Array.from(e)}catch(t){return console.error("Failed to get listening ports:",t.message),[80,443,3e3,3001,4200,5e3,5173,8e3,8080,9e3]}}function _4(r,e=2e3){return new Promise(t=>{let n=Vk.default.request({host:"localhost",port:r,method:"GET",path:"/",timeout:e},i=>{i.on("data",()=>{}),i.on("end",()=>{}),t({active:!0,protocol:"http",status:i.statusCode})});n.on("error",i=>{t({active:!1,error:i.message})}),n.on("timeout",()=>{n.destroy(),t({active:!1,error:"timeout"})}),n.end()})}function b4(r,e=2e3){return new Promise(t=>{let n=Kk.default.request({host:"localhost",port:r,method:"GET",path:"/",timeout:e,rejectUnauthorized:!1},i=>{i.on("data",()=>{}),i.on("end",()=>{}),t({active:!0,protocol:"https",status:i.statusCode})});n.on("error",i=>{t({active:!1,error:i.message})}),n.on("timeout",()=>{n.destroy(),t({active:!1,error:"timeout"})}),n.end()})}async function w4(r){let[e,t]=await Promise.all([_4(r),b4(r)]);return t.active?{port:r,...t}:e.active?{port:r,...e}:{port:r,active:!1}}async function Jk(){let r=await y4();return(await Promise.all(r.map(t=>w4(t)))).filter(t=>t.active).map(t=>({port:t.port,protocol:t.protocol,url:`${t.protocol}://localhost:${t.port}`,name:`localhost:${t.port}`,status:t.status})).sort((t,n)=>t.port-n.port)}var Qk=X(require("crypto"),1),S4=process.env.API_KEY_SECRET||"9remote-api-key-secret";function E4(){let r="abcdefghijklmnopqrstuvwxyz0123456789",e="";for(let t=0;t<4;t++)e+=r.charAt(Math.floor(Math.random()*r.length));return e}function Zk(r,e){return Qk.default.createHmac("sha256",S4).update(r+e).digest("hex").slice(0,6)}function eO(r){let e=r.slice(0,8),t=E4(),n=Zk(e,t);return{key:`sk-${e}-${t}-${n}`,keyId:t}}function T4(r){if(!r||!r.startsWith("sk-"))return null;let e=r.split("-");if(e.length===4){let[,t,n,i]=e,s=Zk(t,n);return i!==s?null:{machineId:t,keyId:n}}return null}function Qu(r){return T4(r)!==null}async function tO(r,e){let t=r.headers.authorization;if(!t||!t.startsWith("Bearer ")){e.setHeader("Content-Type","application/json"),e.writeHead(401),e.end(JSON.stringify({error:"Unauthorized: Missing API key"}));return}let n=t.slice(7);if(!Qu(n)){e.setHeader("Content-Type","application/json"),e.writeHead(401),e.end(JSON.stringify({error:"Unauthorized: Invalid API key"}));return}let i=await Jk();e.setHeader("Content-Type","application/json"),e.writeHead(200),e.end(JSON.stringify(i))}cl();var iO=require("url");var Zu=X(require("path"),1),sO=X(require("os"),1);vt();var rO=X(require("path"),1),nO=X(require("os"),1);var hK=rO.default.join(nO.default.homedir(),".9remote","pids");mh();var Na={checkIntervalMs:36e5,connectCheckDebounceMs:9e5,maxRetry:3,retryDelayMs:3e3,verifyTimeoutMs:15e3,lockTtlMs:3e5,lockFile:"update.lock"};var vK={orange:no.rgb(230,138,110),orangeDim:no.rgb(200,120,95)};var TK=Zu.default.dirname((0,iO.fileURLToPath)(__importMetaUrl));var CK=Zu.default.join(sO.default.homedir(),".9remote","cloudflared.pid");function oO(r,e){let t=r.split(".").map(Number),n=e.split(".").map(Number);for(let i=0;i<3;i++){if(n[i]>t[i])return!0;if(n[i]<t[i])return!1}return!1}var AK=Zu.default.join(oe.STATE,Na.lockFile);Un();Gt();vt();ys();var cO=X(aO(),1),Zg=X(require("crypto"),1),{machineIdSync:C4}=cO.default;async function lO(r=null){let e=r||process.env.MACHINE_ID_SALT||"9remote-salt";try{let t=C4();return Zg.default.createHash("sha256").update(t+e).digest("hex").substring(0,16)}catch(t){return console.error("Error getting machine ID:",t),Zg.default.randomUUID().replace(/-/g,"").substring(0,16)}}Un();async function uO(r,e){let t=zw(),n=t.workerUrl||"https://9remote.cc";if(!t.permanentKey){he(e,400,"No permanent key set");return}try{let s=await(await ao(`${n}/api/temp-key/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.permanentKey,expiryMinutes:30})})).json(),o=`${n}/login?k=${s.tempKey}`;hn({oneTimeKey:s.tempKey,oneTimeKeyExpiresAt:s.expiresAt,qrUrl:o}),ee(e,{oneTimeKey:s.tempKey,expiresAt:s.expiresAt,qrUrl:o})}catch(i){he(e,500,i.message)}}async function pO(r,e){try{let t=await lO(),{key:n}=eO(t),i=Aw();Rw(t,n,i?.name||"Default"),hn({permanentKey:n}),ee(e,{ok:!0,permanentKey:n})}catch(t){he(e,500,t.message)}}Gt();async function fO(r,e){let t=await It(r,e);if(!t)return;let n=tk(t.socketId);ee(e,{ok:n})}async function dO(r,e){let t=await It(r,e);if(!t)return;let n=nk(t.socketId);ee(e,{ok:n})}function hO(r,e){ee(e,{pending:zR()})}function mO(r,e){ee(e,{devices:qR()})}function gO(r,e){ee(e,{rejected:XR()})}async function vO(r,e){let t=await It(r,e);if(!t)return;let n=rk(t.deviceId);ee(e,{ok:n})}async function xO(r,e){let t=await It(r,e);t&&(Vu(t.deviceId),Qs(t.deviceId),ee(e))}async function yO(r,e){let t=await It(r,e);t&&(Vu(t.deviceId),HR(t.deviceId),ee(e))}async function _O(r,e){let t=await It(r,e);if(!t)return;let n=Vu(t.deviceId);ee(e,{disconnected:n})}function bO(r,e){ee(e,{enabled:zu()})}async function wO(r,e){let t=await It(r,e);if(!t)return;let n=UR(t.deviceId,t.label);ee(e,{ok:n})}async function SO(r,e){let t=await It(r,e);if(!t)return;let n=QR(!!t.enabled);ee(e,{enabled:n})}Gt();var EO={},A4=1e4;function TO(r,e){if(e)return{type:e.type||"stop",sessionId:e.sessionId||"",tool:e.tool||"claude"};let t=JSON.parse(r||"{}");return{type:t.type||"stop",sessionId:t.sessionId||"",tool:t.tool||"claude"}}async function CO(r,e){let t="";await new Promise(n=>{r.on("data",i=>t+=i),r.on("end",n)});try{RO(TO(t,null)),ee(e,{success:!0})}catch{he(e,400,"Invalid JSON")}}function AO(r,e,{query:t}){RO(TO(null,t)),ee(e,{success:!0})}function RO({type:r,sessionId:e,tool:t}){let n=Date.now(),i=Ca();if(!i||!e)return;let s={type:r,sessionId:e,tool:t,timestamp:n};if(IT(e,s),wt(i,"chatNotification",s),!AT())return;let o=`${e}:${r}`;n-(EO[o]||0)<A4||(EO[o]=n,PT(s))}Gt();Pl();ys();bt();Un();function kO(){return{mode:bh(),active:_h(),presets:Object.keys(Z.sleepInhibit?.presets||{})}}function OO(r,e){ee(e,kO())}async function PO(r,e){let t=await It(r,e);if(!t)return;let n=Vo(t.mode);Cw({sleepInhibitMode:n});let i=kO();St("sleepInhibit",i),ee(e,i)}Gt();async function MO(r,e){try{let t=await wl();ee(e,{sessions:t})}catch(t){he(e,500,t.message)}}async function IO(r,e){let t=await It(r,e);if(t){if(!t.sessionId)return he(e,400,"sessionId required");try{await di(t.sessionId),ee(e)}catch(n){he(e,500,n.message)}}}Pl();ys();bt();Fv();var Kn=Rn("server"),Yn=(0,BO.fileURLToPath)(new URL(".",__importMetaUrl)),jO=process.env.NODE_ENV==="development",R4=5173,ev=(0,Oi.existsSync)((0,tr.join)(Yn,"ui","dist"))?(0,tr.join)(Yn,"ui","dist"):(0,tr.join)(Yn,"ui"),k4={".html":"text/html",".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff"};function O4(r,e,t){let n=(0,ep.request)({hostname:"localhost",port:R4,path:r.url,method:r.method,headers:r.headers},i=>{e.writeHead(i.statusCode,i.headers),i.pipe(e)});n.on("error",()=>t?t():void(e.writeHead(502),e.end("Vite dev server not ready"))),r.pipe(n)}function NO(r,e){if(!(0,Oi.existsSync)(e))return!1;let t=k4[(0,tr.extname)(e)]||"application/octet-stream";return r.setHeader("Content-Type",t),r.writeHead(200),r.end((0,Oi.readFileSync)(e)),!0}async function tv(r){try{let e=await ao(Ap);if(!e.ok)return;let{version:t}=await e.json();t&&oO(r,t)&&(Yw({version:t}),St("updateAvailable",{version:t}),KT())}catch{}}var LO=0;function P4(r){let e=Date.now();e-LO<Na.connectCheckDebounceMs||(LO=e,tv(r))}function M4(r,e){if(process.env.CODESPACES!=="true"){he(e,400,"Not running on Codespaces");return}let t=process.env.CODESPACE_NAME;if(!t){he(e,400,"Codespace name not found");return}let n=Ca();n&&n.emit("codespace:stopping"),ee(e,{success:!0,message:"Stopping codespace..."}),setTimeout(()=>(0,tp.execFile)("gh",["codespace","stop","-c",t],{windowsHide:!0}),500)}var FO;async function DO(r,e,{pathname:t}){let n=r.headers.authorization;if(!n||!n.startsWith("Bearer ")||!Qu(n.slice(7))){he(e,401,"Unauthorized");return}let{parseJsonBody:i}=await Promise.resolve().then(()=>(Gt(),Ii)),s=await i(r,e);if(s){if(!s.port){he(e,400,"Port required");return}t.endsWith("start")?qk(s.port):Wk(s.port),ee(e,{success:!0})}}function I4(r,e,{pathname:t,search:n}){let i=t.match(/^\/proxy\/(\d+)(\/.*)?$/);i?zk(FO,r,e,i[1],i[2]||"/",n):he(e,404,"Not found")}var N4=[{path:"/api/health",method:"GET",public:!0,handler:(r,e)=>ee(e,{status:"ok",timestamp:Date.now()})},{path:"/api/version",method:"GET",public:!0,handler:(r,e)=>{ee(e,{version:"2.0.58"})}},{path:"/api/notify",method:"POST",public:!0,handler:CO},{path:"/api/notify",method:"GET",public:!0,handler:AO},{path:"/proxy/*",method:"*",public:!0,handler:I4},{path:"/api/ui/events",method:"GET",handler:rS},{path:"/api/local-token",method:"GET",handler:Qw},{path:"/api/ui/state",method:"GET",handler:nS},{path:"/api/ui/state",method:"POST",handler:iS},{path:"/api/ui/stop",method:"POST",handler:sS},{path:"/api/ui/start",method:"POST",handler:oS},{path:"/api/ui/stop-tunnel",method:"POST",handler:aS},{path:"/api/ui/shutdown",method:"POST",handler:cS},{path:"/api/update",method:"POST",handler:lS},{path:"/api/key/one-time",method:"POST",handler:uO},{path:"/api/key/regenerate",method:"POST",handler:pO},{path:"/api/device/approve",method:"POST",handler:fO},{path:"/api/device/reject",method:"POST",handler:dO},{path:"/api/device/pending",method:"GET",handler:hO},{path:"/api/device/approved",method:"GET",handler:mO},{path:"/api/device/rejected",method:"GET",handler:gO},{path:"/api/device/approve-rejected",method:"POST",handler:vO},{path:"/api/device/clear-rejected",method:"POST",handler:xO},{path:"/api/device/remove",method:"POST",handler:yO},{path:"/api/device/label",method:"POST",handler:wO},{path:"/api/device/disconnect",method:"POST",handler:_O},{path:"/api/device/auto-approve",method:"GET",handler:bO},{path:"/api/device/auto-approve",method:"POST",handler:SO},{path:"/api/connections",method:"GET",handler:uS},{path:"/api/logs",method:"GET",handler:pS},{path:"/api/permissions",method:"GET",handler:dS},{path:"/api/permissions/request",method:"POST",handler:gS},{path:"/api/desktop/toggle",method:"POST",handler:fS},{path:"/api/autostart",method:"GET",handler:hS},{path:"/api/autostart",method:"POST",handler:mS},{path:"/api/sleep-inhibit",method:"GET",handler:OO},{path:"/api/sleep-inhibit",method:"POST",handler:PO},{path:"/api/sessions",method:"GET",handler:MO},{path:"/api/sessions/delete",method:"POST",handler:IO},{path:"/api/local-sites",method:"*",public:!0,handler:tO},{path:"/api/codespace/stop",method:"POST",handler:M4},{path:"/api/proxy/start",method:"POST",public:!0,handler:DO},{path:"/api/proxy/end",method:"POST",public:!0,handler:DO}];var L4=parseInt(process.env.PORT||"2208",10),Da=null;function D4(){if(!jO)return;let r=(0,tr.join)(Yn,"vite.config.js");if(!(0,Oi.existsSync)(r))return;let e=(0,Oi.existsSync)((0,tr.join)(Yn,"node_modules",".bin","vite"))?(0,tr.join)(Yn,"node_modules",".bin","vite"):(0,tr.join)(Yn,"..","node_modules",".bin","vite");Da=(0,tp.spawn)("node",[e,"--config",r],{cwd:Yn,stdio:"ignore",detached:!1}),Da.on("error",()=>{}),Da.unref()}async function $O(){let r=ph(),e=r.sleepInhibitMode;e||(r.sleepInhibit===!1?e="never":e=Z.sleepInhibit?.defaultMode||"never"),Vo(e),await VT(),FO=Gk(),D4();let n=Tp(N4,{fallback:(a,c,{pathname:u})=>{if(u.startsWith("/api/")||u.startsWith("/socket.io")){he(c,404,"Not found");return}let p=!!a.headers["cf-connecting-ip"],f=a.socket.remoteAddress==="127.0.0.1"||a.socket.remoteAddress==="::1";if(p||!f){he(c,403,"Forbidden");return}let m=()=>{let y=u==="/"||u===""?(0,tr.join)(ev,"index.html"):(0,tr.join)(ev,u);NO(c,y)||NO(c,(0,tr.join)(ev,"index.html"))};if(jO){O4(a,c,m);return}m()}}),i=(0,ep.createServer)(async(a,c)=>{sk(c),!ok(a,c)&&await n(a,c)});zd(),Ww(),Gw(),Nl(),process.platform==="darwin"&&setInterval(Nl,Mv),await ik(i),i.listen(L4,a=>{if(a)throw a;let c="2.0.58";tv(c),setInterval(()=>tv(c),Na.checkIntervalMs),XT(()=>P4(c))});let s=!1,o=async a=>{if(s)return;s=!0,yh(),Kn.info(`\u{1F6D1} Received ${a}, shutting down gracefully...`);let c=setTimeout(()=>{Kn.error("\u26A0\uFE0F Forced exit"),process.exit(1)},5e3);try{if(i.close(()=>Kn.info("\u2713 HTTP server closed")),Da)try{Da.kill()}catch{}let u=Ca();u&&(u.emit("server:shutdown"),u.close(()=>Kn.info("\u2713 Socket.IO closed"))),await new Promise(p=>setTimeout(p,500)),clearTimeout(c),Kn.info("\u2705 Server stopped cleanly"),process.exit(0)}catch(u){Kn.error(`\u274C Error during shutdown: ${u?.message||u}`),clearTimeout(c),process.exit(1)}};return process.on("SIGINT",()=>o("SIGINT")),process.on("SIGTERM",()=>o("SIGTERM")),process.platform==="win32"&&process.on("SIGBREAK",()=>o("SIGBREAK")),process.on("uncaughtException",a=>{Kn.error(`\u26A0\uFE0F uncaughtException: ${a?.stack||a}`)}),process.on("unhandledRejection",a=>{Kn.error(`\u26A0\uFE0F unhandledRejection: ${a?.stack||a}`)}),i}$O();0&&(module.exports={startServer});
|
|
264
|
+
`);for(let s of i){let o=s.match(/[:\*\]](\d{2,5})(?:\s|$)/g);if(o)for(let a of o){let c=parseInt(a.replace(/[:\*\]\s]/g,""),10);c>0&&c<=65535&&(c===80||c===443||c>=1024)&&e.add(c)}}return Array.from(e)}catch(t){return console.error("Failed to get listening ports:",t.message),[80,443,3e3,3001,4200,5e3,5173,8e3,8080,9e3]}}function _4(r,e=2e3){return new Promise(t=>{let n=Vk.default.request({host:"localhost",port:r,method:"GET",path:"/",timeout:e},i=>{i.on("data",()=>{}),i.on("end",()=>{}),t({active:!0,protocol:"http",status:i.statusCode})});n.on("error",i=>{t({active:!1,error:i.message})}),n.on("timeout",()=>{n.destroy(),t({active:!1,error:"timeout"})}),n.end()})}function b4(r,e=2e3){return new Promise(t=>{let n=Kk.default.request({host:"localhost",port:r,method:"GET",path:"/",timeout:e,rejectUnauthorized:!1},i=>{i.on("data",()=>{}),i.on("end",()=>{}),t({active:!0,protocol:"https",status:i.statusCode})});n.on("error",i=>{t({active:!1,error:i.message})}),n.on("timeout",()=>{n.destroy(),t({active:!1,error:"timeout"})}),n.end()})}async function w4(r){let[e,t]=await Promise.all([_4(r),b4(r)]);return t.active?{port:r,...t}:e.active?{port:r,...e}:{port:r,active:!1}}async function Jk(){let r=await y4();return(await Promise.all(r.map(t=>w4(t)))).filter(t=>t.active).map(t=>({port:t.port,protocol:t.protocol,url:`${t.protocol}://localhost:${t.port}`,name:`localhost:${t.port}`,status:t.status})).sort((t,n)=>t.port-n.port)}var Qk=X(require("crypto"),1),S4=process.env.API_KEY_SECRET||"9remote-api-key-secret";function E4(){let r="abcdefghijklmnopqrstuvwxyz0123456789",e="";for(let t=0;t<4;t++)e+=r.charAt(Math.floor(Math.random()*r.length));return e}function Zk(r,e){return Qk.default.createHmac("sha256",S4).update(r+e).digest("hex").slice(0,6)}function eO(r){let e=r.slice(0,8),t=E4(),n=Zk(e,t);return{key:`sk-${e}-${t}-${n}`,keyId:t}}function T4(r){if(!r||!r.startsWith("sk-"))return null;let e=r.split("-");if(e.length===4){let[,t,n,i]=e,s=Zk(t,n);return i!==s?null:{machineId:t,keyId:n}}return null}function Qu(r){return T4(r)!==null}async function tO(r,e){let t=r.headers.authorization;if(!t||!t.startsWith("Bearer ")){e.setHeader("Content-Type","application/json"),e.writeHead(401),e.end(JSON.stringify({error:"Unauthorized: Missing API key"}));return}let n=t.slice(7);if(!Qu(n)){e.setHeader("Content-Type","application/json"),e.writeHead(401),e.end(JSON.stringify({error:"Unauthorized: Invalid API key"}));return}let i=await Jk();e.setHeader("Content-Type","application/json"),e.writeHead(200),e.end(JSON.stringify(i))}cl();var iO=require("url");var Zu=X(require("path"),1),sO=X(require("os"),1);vt();var rO=X(require("path"),1),nO=X(require("os"),1);var hK=rO.default.join(nO.default.homedir(),".9remote","pids");mh();var Na={checkIntervalMs:36e5,connectCheckDebounceMs:9e5,maxRetry:3,retryDelayMs:3e3,verifyTimeoutMs:15e3,lockTtlMs:3e5,lockFile:"update.lock"};var vK={orange:no.rgb(230,138,110),orangeDim:no.rgb(200,120,95)};var TK=Zu.default.dirname((0,iO.fileURLToPath)(__importMetaUrl));var CK=Zu.default.join(sO.default.homedir(),".9remote","cloudflared.pid");function oO(r,e){let t=r.split(".").map(Number),n=e.split(".").map(Number);for(let i=0;i<3;i++){if(n[i]>t[i])return!0;if(n[i]<t[i])return!1}return!1}var AK=Zu.default.join(oe.STATE,Na.lockFile);Un();Gt();vt();ys();var cO=X(aO(),1),Zg=X(require("crypto"),1),{machineIdSync:C4}=cO.default;async function lO(r=null){let e=r||process.env.MACHINE_ID_SALT||"9remote-salt";try{let t=C4();return Zg.default.createHash("sha256").update(t+e).digest("hex").substring(0,16)}catch(t){return console.error("Error getting machine ID:",t),Zg.default.randomUUID().replace(/-/g,"").substring(0,16)}}Un();async function uO(r,e){let t=zw(),n=t.workerUrl||"https://9remote.cc";if(!t.permanentKey){he(e,400,"No permanent key set");return}try{let s=await(await ao(`${n}/api/temp-key/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.permanentKey,expiryMinutes:30})})).json(),o=`${n}/login?k=${s.tempKey}`;hn({oneTimeKey:s.tempKey,oneTimeKeyExpiresAt:s.expiresAt,qrUrl:o}),ee(e,{oneTimeKey:s.tempKey,expiresAt:s.expiresAt,qrUrl:o})}catch(i){he(e,500,i.message)}}async function pO(r,e){try{let t=await lO(),{key:n}=eO(t),i=Aw();Rw(t,n,i?.name||"Default"),hn({permanentKey:n}),ee(e,{ok:!0,permanentKey:n})}catch(t){he(e,500,t.message)}}Gt();async function fO(r,e){let t=await It(r,e);if(!t)return;let n=tk(t.socketId);ee(e,{ok:n})}async function dO(r,e){let t=await It(r,e);if(!t)return;let n=nk(t.socketId);ee(e,{ok:n})}function hO(r,e){ee(e,{pending:zR()})}function mO(r,e){ee(e,{devices:qR()})}function gO(r,e){ee(e,{rejected:XR()})}async function vO(r,e){let t=await It(r,e);if(!t)return;let n=rk(t.deviceId);ee(e,{ok:n})}async function xO(r,e){let t=await It(r,e);t&&(Vu(t.deviceId),Qs(t.deviceId),ee(e))}async function yO(r,e){let t=await It(r,e);t&&(Vu(t.deviceId),HR(t.deviceId),ee(e))}async function _O(r,e){let t=await It(r,e);if(!t)return;let n=Vu(t.deviceId);ee(e,{disconnected:n})}function bO(r,e){ee(e,{enabled:zu()})}async function wO(r,e){let t=await It(r,e);if(!t)return;let n=UR(t.deviceId,t.label);ee(e,{ok:n})}async function SO(r,e){let t=await It(r,e);if(!t)return;let n=QR(!!t.enabled);ee(e,{enabled:n})}Gt();var EO={},A4=1e4;function TO(r,e){if(e)return{type:e.type||"stop",sessionId:e.sessionId||"",tool:e.tool||"claude"};let t=JSON.parse(r||"{}");return{type:t.type||"stop",sessionId:t.sessionId||"",tool:t.tool||"claude"}}async function CO(r,e){let t="";await new Promise(n=>{r.on("data",i=>t+=i),r.on("end",n)});try{RO(TO(t,null)),ee(e,{success:!0})}catch{he(e,400,"Invalid JSON")}}function AO(r,e,{query:t}){RO(TO(null,t)),ee(e,{success:!0})}function RO({type:r,sessionId:e,tool:t}){let n=Date.now(),i=Ca();if(!i||!e)return;let s={type:r,sessionId:e,tool:t,timestamp:n};if(IT(e,s),wt(i,"chatNotification",s),!AT())return;let o=`${e}:${r}`;n-(EO[o]||0)<A4||(EO[o]=n,PT(s))}Gt();Pl();ys();bt();Un();function kO(){return{mode:bh(),active:_h(),presets:Object.keys(Z.sleepInhibit?.presets||{})}}function OO(r,e){ee(e,kO())}async function PO(r,e){let t=await It(r,e);if(!t)return;let n=Vo(t.mode);Cw({sleepInhibitMode:n});let i=kO();St("sleepInhibit",i),ee(e,i)}Gt();async function MO(r,e){try{let t=await wl();ee(e,{sessions:t})}catch(t){he(e,500,t.message)}}async function IO(r,e){let t=await It(r,e);if(t){if(!t.sessionId)return he(e,400,"sessionId required");try{await di(t.sessionId),ee(e)}catch(n){he(e,500,n.message)}}}Pl();ys();bt();Fv();var Kn=Rn("server"),Yn=(0,BO.fileURLToPath)(new URL(".",__importMetaUrl)),jO=process.env.NODE_ENV==="development",R4=5173,ev=(0,Oi.existsSync)((0,tr.join)(Yn,"ui","dist"))?(0,tr.join)(Yn,"ui","dist"):(0,tr.join)(Yn,"ui"),k4={".html":"text/html",".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff"};function O4(r,e,t){let n=(0,ep.request)({hostname:"localhost",port:R4,path:r.url,method:r.method,headers:r.headers},i=>{e.writeHead(i.statusCode,i.headers),i.pipe(e)});n.on("error",()=>t?t():void(e.writeHead(502),e.end("Vite dev server not ready"))),r.pipe(n)}function NO(r,e){if(!(0,Oi.existsSync)(e))return!1;let t=k4[(0,tr.extname)(e)]||"application/octet-stream";return r.setHeader("Content-Type",t),r.writeHead(200),r.end((0,Oi.readFileSync)(e)),!0}async function tv(r){try{let e=await ao(Ap);if(!e.ok)return;let{version:t}=await e.json();t&&oO(r,t)&&(Yw({version:t}),St("updateAvailable",{version:t}),KT())}catch{}}var LO=0;function P4(r){let e=Date.now();e-LO<Na.connectCheckDebounceMs||(LO=e,tv(r))}function M4(r,e){if(process.env.CODESPACES!=="true"){he(e,400,"Not running on Codespaces");return}let t=process.env.CODESPACE_NAME;if(!t){he(e,400,"Codespace name not found");return}let n=Ca();n&&n.emit("codespace:stopping"),ee(e,{success:!0,message:"Stopping codespace..."}),setTimeout(()=>(0,tp.execFile)("gh",["codespace","stop","-c",t],{windowsHide:!0}),500)}var FO;async function DO(r,e,{pathname:t}){let n=r.headers.authorization;if(!n||!n.startsWith("Bearer ")||!Qu(n.slice(7))){he(e,401,"Unauthorized");return}let{parseJsonBody:i}=await Promise.resolve().then(()=>(Gt(),Ii)),s=await i(r,e);if(s){if(!s.port){he(e,400,"Port required");return}t.endsWith("start")?qk(s.port):Wk(s.port),ee(e,{success:!0})}}function I4(r,e,{pathname:t,search:n}){let i=t.match(/^\/proxy\/(\d+)(\/.*)?$/);i?zk(FO,r,e,i[1],i[2]||"/",n):he(e,404,"Not found")}var N4=[{path:"/api/health",method:"GET",public:!0,handler:(r,e)=>ee(e,{status:"ok",timestamp:Date.now()})},{path:"/api/version",method:"GET",public:!0,handler:(r,e)=>{ee(e,{version:"2.0.59"})}},{path:"/api/notify",method:"POST",public:!0,handler:CO},{path:"/api/notify",method:"GET",public:!0,handler:AO},{path:"/proxy/*",method:"*",public:!0,handler:I4},{path:"/api/ui/events",method:"GET",handler:rS},{path:"/api/local-token",method:"GET",handler:Qw},{path:"/api/ui/state",method:"GET",handler:nS},{path:"/api/ui/state",method:"POST",handler:iS},{path:"/api/ui/stop",method:"POST",handler:sS},{path:"/api/ui/start",method:"POST",handler:oS},{path:"/api/ui/stop-tunnel",method:"POST",handler:aS},{path:"/api/ui/shutdown",method:"POST",handler:cS},{path:"/api/update",method:"POST",handler:lS},{path:"/api/key/one-time",method:"POST",handler:uO},{path:"/api/key/regenerate",method:"POST",handler:pO},{path:"/api/device/approve",method:"POST",handler:fO},{path:"/api/device/reject",method:"POST",handler:dO},{path:"/api/device/pending",method:"GET",handler:hO},{path:"/api/device/approved",method:"GET",handler:mO},{path:"/api/device/rejected",method:"GET",handler:gO},{path:"/api/device/approve-rejected",method:"POST",handler:vO},{path:"/api/device/clear-rejected",method:"POST",handler:xO},{path:"/api/device/remove",method:"POST",handler:yO},{path:"/api/device/label",method:"POST",handler:wO},{path:"/api/device/disconnect",method:"POST",handler:_O},{path:"/api/device/auto-approve",method:"GET",handler:bO},{path:"/api/device/auto-approve",method:"POST",handler:SO},{path:"/api/connections",method:"GET",handler:uS},{path:"/api/logs",method:"GET",handler:pS},{path:"/api/permissions",method:"GET",handler:dS},{path:"/api/permissions/request",method:"POST",handler:gS},{path:"/api/desktop/toggle",method:"POST",handler:fS},{path:"/api/autostart",method:"GET",handler:hS},{path:"/api/autostart",method:"POST",handler:mS},{path:"/api/sleep-inhibit",method:"GET",handler:OO},{path:"/api/sleep-inhibit",method:"POST",handler:PO},{path:"/api/sessions",method:"GET",handler:MO},{path:"/api/sessions/delete",method:"POST",handler:IO},{path:"/api/local-sites",method:"*",public:!0,handler:tO},{path:"/api/codespace/stop",method:"POST",handler:M4},{path:"/api/proxy/start",method:"POST",public:!0,handler:DO},{path:"/api/proxy/end",method:"POST",public:!0,handler:DO}];var L4=parseInt(process.env.PORT||"2208",10),Da=null;function D4(){if(!jO)return;let r=(0,tr.join)(Yn,"vite.config.js");if(!(0,Oi.existsSync)(r))return;let e=(0,Oi.existsSync)((0,tr.join)(Yn,"node_modules",".bin","vite"))?(0,tr.join)(Yn,"node_modules",".bin","vite"):(0,tr.join)(Yn,"..","node_modules",".bin","vite");Da=(0,tp.spawn)("node",[e,"--config",r],{cwd:Yn,stdio:"ignore",detached:!1}),Da.on("error",()=>{}),Da.unref()}async function $O(){let r=ph(),e=r.sleepInhibitMode;e||(r.sleepInhibit===!1?e="never":e=Z.sleepInhibit?.defaultMode||"never"),Vo(e),await VT(),FO=Gk(),D4();let n=Tp(N4,{fallback:(a,c,{pathname:u})=>{if(u.startsWith("/api/")||u.startsWith("/socket.io")){he(c,404,"Not found");return}let p=!!a.headers["cf-connecting-ip"],f=a.socket.remoteAddress==="127.0.0.1"||a.socket.remoteAddress==="::1";if(p||!f){he(c,403,"Forbidden");return}let m=()=>{let y=u==="/"||u===""?(0,tr.join)(ev,"index.html"):(0,tr.join)(ev,u);NO(c,y)||NO(c,(0,tr.join)(ev,"index.html"))};if(jO){O4(a,c,m);return}m()}}),i=(0,ep.createServer)(async(a,c)=>{sk(c),!ok(a,c)&&await n(a,c)});zd(),Ww(),Gw(),Nl(),process.platform==="darwin"&&setInterval(Nl,Mv),await ik(i),i.listen(L4,a=>{if(a)throw a;let c="2.0.59";tv(c),setInterval(()=>tv(c),Na.checkIntervalMs),XT(()=>P4(c))});let s=!1,o=async a=>{if(s)return;s=!0,yh(),Kn.info(`\u{1F6D1} Received ${a}, shutting down gracefully...`);let c=setTimeout(()=>{Kn.error("\u26A0\uFE0F Forced exit"),process.exit(1)},5e3);try{if(i.close(()=>Kn.info("\u2713 HTTP server closed")),Da)try{Da.kill()}catch{}let u=Ca();u&&(u.emit("server:shutdown"),u.close(()=>Kn.info("\u2713 Socket.IO closed"))),await new Promise(p=>setTimeout(p,500)),clearTimeout(c),Kn.info("\u2705 Server stopped cleanly"),process.exit(0)}catch(u){Kn.error(`\u274C Error during shutdown: ${u?.message||u}`),clearTimeout(c),process.exit(1)}};return process.on("SIGINT",()=>o("SIGINT")),process.on("SIGTERM",()=>o("SIGTERM")),process.platform==="win32"&&process.on("SIGBREAK",()=>o("SIGBREAK")),process.on("uncaughtException",a=>{Kn.error(`\u26A0\uFE0F uncaughtException: ${a?.stack||a}`)}),process.on("unhandledRejection",a=>{Kn.error(`\u26A0\uFE0F unhandledRejection: ${a?.stack||a}`)}),i}$O();0&&(module.exports={startServer});
|
|
265
265
|
/*! Bundled license information:
|
|
266
266
|
|
|
267
267
|
negotiator/index.js:
|