@easbot/gateway 0.1.13 → 0.1.15
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/README.en.md +2 -0
- package/README.md +5 -3
- package/dist/chunks/{chunk-53BBS4BZ.cjs → chunk-BOHNPDOJ.cjs} +1 -1
- package/dist/chunks/{chunk-56QXYDMF.cjs → chunk-CTTZF7B6.cjs} +1 -1
- package/dist/chunks/{chunk-JJLKV5TO.cjs → chunk-EKLLH53Y.cjs} +7 -7
- package/dist/chunks/{chunk-53LJ4W4U.cjs → chunk-EOLBEWUW.cjs} +1 -1
- package/dist/chunks/chunk-ETYFY7SI.mjs +9 -0
- package/dist/chunks/{chunk-KZSKMJ7I.mjs → chunk-J2DSTELL.mjs} +1 -1
- package/dist/chunks/{chunk-YM25IJHX.mjs → chunk-VVZG6LF6.mjs} +1 -1
- package/dist/chunks/{chunk-X7GOOL6H.mjs → chunk-YAKKDECJ.mjs} +1 -1
- package/dist/chunks/{global-OQXFOP3G.cjs → global-K4U25JQK.cjs} +1 -1
- package/dist/chunks/{global-4ADGPO6X.mjs → global-KXPT44QD.mjs} +1 -1
- package/dist/chunks/package-2UGUDLKV.cjs +1 -0
- package/dist/chunks/package-UZJDAOIA.mjs +1 -0
- package/dist/chunks/server-3CBE5XNJ.cjs +1 -0
- package/dist/chunks/server-GVEVKN4C.mjs +1 -0
- package/dist/cli.cjs +3 -3
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +8 -8
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.mjs +1 -1
- package/package.json +25 -23
- package/dist/chunks/chunk-UMFMKA5B.mjs +0 -9
- package/dist/chunks/package-4AZWR5ML.cjs +0 -1
- package/dist/chunks/package-P2T6DXEE.mjs +0 -1
- package/dist/chunks/server-RYQHSEAD.mjs +0 -1
- package/dist/chunks/server-TIKLUNVP.cjs +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {w as w$1,a as a$1,R as R$1,O,P as P$1}from'./chunk-UMFMKA5B.mjs';import {a}from'./chunk-SJNPXLNN.mjs';import {e}from'./chunk-TY6W6O7O.mjs';import*as m from'fs';import m__default from'fs';import*as z from'path';import {HookEvent}from'@easbot/plugin';import {createServer}from'@easbot/utils';import {WebSocketServer}from'ws';import V from'https';import K from'http';a();a();a();var x=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:lock"}));e(this,"config");e(this,"locks",new Map);e(this,"cleanupTimer",null);this.config={defaultTimeout:e$1.defaultTimeout??6e4,checkInterval:e$1.checkInterval??1e4};}tryAcquire(e,t,s,n){let r=this.locks.get(e);if(r)if(this.isLockExpired(r))this.log.warn("lock expired, releasing",{sessionId:e,oldHolder:r.holderId,newHolder:s}),this.locks.delete(e);else return this.log.debug("lock already held",{sessionId:e,holder:r.holderId,messageId:r.messageId}),false;let a={sessionId:e,messageId:t,holderId:s,acquiredAt:Date.now(),timeout:n??this.config.defaultTimeout};return this.locks.set(e,a),this.log.debug("lock acquired",{sessionId:e,messageId:t,subscriberId:s}),true}release(e,t){let s=this.locks.get(e);return s?s.holderId!==t?(this.log.warn("cannot release lock held by another",{sessionId:e,holder:s.holderId,requester:t}),false):(this.locks.delete(e),this.log.debug("lock released",{sessionId:e,subscriberId:t}),true):(this.log.debug("no lock to release",{sessionId:e}),false)}forceRelease(e){let t=this.locks.get(e);return t?(this.locks.delete(e),this.log.warn("lock force released",{sessionId:e,holder:t.holderId,messageId:t.messageId}),true):false}isLockExpired(e){return Date.now()-e.acquiredAt>e.timeout}getLock(e){return this.locks.get(e)}isLocked(e){let t=this.locks.get(e);return t?this.isLockExpired(t)?(this.locks.delete(e),false):true:false}getHolder(e){let t=this.locks.get(e);if(!(!t||this.isLockExpired(t)))return t.holderId}startCleanup(){this.cleanupTimer||(this.cleanupTimer=setInterval(()=>{this.cleanupExpired();},this.config.checkInterval),this.log.info("lock cleanup started",{interval:this.config.checkInterval}));}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null,this.log.info("lock cleanup stopped"));}cleanupExpired(){let e=0;for(let[t,s]of this.locks)this.isLockExpired(s)&&(this.locks.delete(t),e++,this.log.warn("expired lock cleaned up",{sessionId:t,holder:s.holderId,messageId:s.messageId}));return e>0&&this.log.info("cleaned up expired locks",{count:e}),e}getAllLocks(){return [...this.locks.values()]}getLockCount(){return this.locks.size}};a();var k=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:retry"}));e(this,"policy");e(this,"retryQueue",new Map);e(this,"retryTimer",null);e(this,"handlers",new Map);this.policy={maxRetries:e$1.maxRetries??3,initialDelay:e$1.initialDelay??1e3,maxDelay:e$1.maxDelay??3e4,backoffMultiplier:e$1.backoffMultiplier??2};}registerHandler(e,t){this.handlers.set(e,t);}unregisterHandler(e){this.handlers.delete(e);}scheduleRetry(e,t){let s=e.id,n=this.retryQueue.get(s);if(n||(n={messageId:s,retryCount:0,nextRetryAt:0,errors:[]},this.retryQueue.set(s,n)),n.errors.push({error:t.message,timestamp:Date.now()}),n.retryCount>=this.policy.maxRetries)return this.log.error("max retries exceeded",{messageId:s,retryCount:n.retryCount,maxRetries:this.policy.maxRetries}),false;let r=Math.min(this.policy.initialDelay*this.policy.backoffMultiplier**n.retryCount,this.policy.maxDelay);return n.retryCount++,n.nextRetryAt=Date.now()+r,this.log.warn("retry scheduled",{messageId:s,retryCount:n.retryCount,delay:r,error:t.message}),true}getPendingRetries(){let e=Date.now(),t=[];for(let s of this.retryQueue.values())s.nextRetryAt<=e&&s.retryCount<=this.policy.maxRetries&&t.push(s);return t}async executeRetry(e){if(!this.handlers.get(e.messageId))return this.log.warn("no handler for retry",{messageId:e.messageId}),false;this.retryQueue.delete(e.messageId);try{return this.log.info("executing retry",{messageId:e.messageId,retryCount:e.retryCount}),!0}catch(s){return this.log.error("retry execution failed",{messageId:e.messageId,error:String(s)}),false}}clearRetry(e){this.retryQueue.delete(e),this.handlers.delete(e),this.log.debug("retry cleared",{messageId:e});}startProcessing(){this.retryTimer||(this.retryTimer=setInterval(async()=>{let e=this.getPendingRetries();for(let t of e)await this.executeRetry(t);},1e3),this.log.info("retry processing started"));}stopProcessing(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null,this.log.info("retry processing stopped"));}getStats(){let e=0;for(let t of this.retryQueue.values())e+=t.errors.length;return {pendingCount:this.retryQueue.size,totalErrors:e}}};a();a();function W(c,e,t,s){return {id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:c,type:e,content:t,metadata:{channel:{platform:s?.channel?.platform??"api",channelId:s?.channel?.channelId??"default",userId:s?.channel?.userId,chatId:s?.channel?.chatId,...Object.fromEntries(Object.entries(s?.channel??{}).filter(([n])=>!["platform","channelId","userId","chatId"].includes(n)))},context:s?.context,agent:s?.agent},timestamp:Date.now()}}function q(c,e,t,s){return W(c,e,[{type:"text",text:t}],s)}a();function E(c){let e=[c.platform,c.channelId];return c.chatId&&e.push(c.chatId),c.userId&&e.push(c.userId),e.join("_")}function D(){return {status:"active",messageCount:0,lastMessageAt:null}}a();function A(c,e){return `sub_${c}_${e}`}a();var _=w$1,v={maxConnections:w$1.maxConnections??1e3,connectionTimeout:w$1.connectionTimeout??6e4,sessionExpireMs:w$1.sessionExpireMs??3e5,heartbeatInterval:w$1.heartbeatInterval??3e4};a();var F={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};a();var U={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3};a();var $={mode:"both",interval:3e4,pushEvents:["register","deregister","status_change"],conflictResolution:"latest",remoteNodes:[]};a();var j={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var P=class{constructor(){e(this,"log",a$1.create({service:"gateway:router"}));e(this,"subscribers",new Map);e(this,"subscriptions",new Map);e(this,"sessionSubscriptions",new Map);e(this,"channelPlugins",new Map);e(this,"lockManager");e(this,"retryManager");e(this,"cancelHandlers",new Set);this.lockManager=new x,this.retryManager=new k,this.lockManager.startCleanup();}onCancel(e){this.cancelHandlers.add(e);}offCancel(e){this.cancelHandlers.delete(e);}async emitCancel(e){for(let t of this.cancelHandlers)try{await t(e);}catch(s){this.log.error("cancel handler error",{error:String(s)});}}async route(e){this.log.debug("routing message",{id:e.id,sessionId:e.sessionId,type:e.type});let t=this.sessionSubscriptions.get(e.sessionId);if(!t||t.size===0)return this.log.debug("no subscribers for session",{sessionId:e.sessionId}),{success:true,broadcastCount:0,dispatchedToSubAgent:false};let s=0,n=null,r=[];for(let a of t){let g=this.subscriptions.get(a);if(!g)continue;let u=this.subscribers.get(g.subscriberId);if(u){if(e.type==="input"){if(!this.lockManager.tryAcquire(e.sessionId,e.id,u.id)){this.log.debug("skipping subscriber, lock held by another",{subscriberId:u.id,holder:this.lockManager.getHolder(e.sessionId)});continue}n=u.id;}try{await u.connection.send(e),s++,u.lastActiveAt=Date.now();}catch(f){this.log.warn("failed to send message to subscriber",{subscriberId:u.id,error:String(f)}),r.push(f instanceof Error?f:new Error(String(f))),n===u.id&&(this.lockManager.release(e.sessionId,u.id),n=null);}}}return this.log.debug("message routed",{id:e.id,broadcastCount:s,errorCount:r.length,processedBy:n}),{success:r.length===0,broadcastCount:s,dispatchedToSubAgent:false,error:r.length>0?r.map(a=>a.message).join("; "):void 0}}async completeMessage(e,t,s,n="completed"){this.lockManager.release(e,s),await this.emitCancel({sessionId:e,messageId:t,processedBy:s,reason:n,timestamp:Date.now()}),this.log.info("message completed",{sessionId:e,messageId:t,subscriberId:s,reason:n});}scheduleRetry(e,t){return this.retryManager.scheduleRetry(e,t)}async subscribe(e,t){let s=A(t.id,e);if(this.subscriptions.has(s))return this.log.debug("already subscribed",{subscriberId:t.id,sessionId:e}),this.subscriptions.get(s);let n={id:s,subscriberId:t.id,sessionId:e,createdAt:Date.now()};return this.subscribers.has(t.id)||this.subscribers.set(t.id,t),this.subscriptions.set(s,n),this.sessionSubscriptions.has(e)||this.sessionSubscriptions.set(e,new Set),this.sessionSubscriptions.get(e).add(s),t.sessions.add(e),this.log.info("subscribed to session",{subscriberId:t.id,sessionId:e,subscriptionId:s}),n}async unsubscribe(e){let t=this.subscriptions.get(e);if(!t){this.log.warn("subscription not found",{subscriptionId:e});return}this.subscriptions.delete(e);let s=this.sessionSubscriptions.get(t.sessionId);s&&(s.delete(e),s.size===0&&this.sessionSubscriptions.delete(t.sessionId));let n=this.subscribers.get(t.subscriberId);n&&n.sessions.delete(t.sessionId),this.log.info("unsubscribed from session",{subscriberId:t.subscriberId,sessionId:t.sessionId,subscriptionId:e});}async unsubscribeAll(e){let t=this.subscribers.get(e);if(!t)return;let s=[...t.sessions];for(let n of s){let r=A(e,n);await this.unsubscribe(r);}this.subscribers.delete(e),this.log.info("unsubscribed all sessions",{subscriberId:e});}async registerChannel(e){if(this.channelPlugins.has(e.id)){this.log.warn("channel plugin already registered",{id:e.id});return}this.channelPlugins.set(e.id,e),this.log.info("channel plugin registered",{id:e.id,platform:e.platform});}async unregisterChannel(e){let t=this.channelPlugins.get(e);if(!t){this.log.warn("channel plugin not found",{id:e});return}await t.stop(),this.channelPlugins.delete(e),this.log.info("channel plugin unregistered",{id:e});}getSubscriberCount(e){let t=this.sessionSubscriptions.get(e);return t?t.size:0}getAllSubscribers(){return [...this.subscribers.values()]}getChannelPlugin(e){return this.channelPlugins.get(e)}getAllChannelPlugins(){return [...this.channelPlugins.values()]}getLockManager(){return this.lockManager}getRetryManager(){return this.retryManager}async shutdown(){this.lockManager.stopCleanup(),this.retryManager.stopProcessing(),this.log.info("router shutdown");}};a();a();a();a();var C=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:message-store"}));e(this,"config");e(this,"messages",new Map);e(this,"sessionMessages",new Map);this.config={storagePath:e$1.storagePath??"./data/gateway-messages",maxRetentionDays:e$1.maxRetentionDays??30,maxRecords:e$1.maxRecords??1e5};}async store(e){let t={message:e,status:"pending",processedBy:null,processedAt:null,retryCount:0,error:null,createdAt:Date.now(),updatedAt:Date.now()};return this.messages.set(e.id,t),this.sessionMessages.has(e.sessionId)||this.sessionMessages.set(e.sessionId,new Set),this.sessionMessages.get(e.sessionId).add(e.id),this.log.debug("message stored",{id:e.id,sessionId:e.sessionId,type:e.type}),t}get(e){return this.messages.get(e)}async updateStatus(e,t,s={}){let n=this.messages.get(e);if(!n){this.log.warn("message not found for status update",{messageId:e});return}n.status=t,n.updatedAt=Date.now(),s.processedBy&&(n.processedBy=s.processedBy),(t==="completed"||t==="failed")&&(n.processedAt=Date.now()),s.error&&(n.error=s.error),this.log.debug("message status updated",{id:e,status:t,processedBy:s.processedBy});}incrementRetry(e){let t=this.messages.get(e);return t?(t.retryCount++,t.updatedAt=Date.now(),t.retryCount):0}isProcessed(e){let t=this.messages.get(e);return t?t.status==="completed"||t.status==="processing":false}getSessionHistory(e,t=100){let s=this.sessionMessages.get(e);if(!s)return [];let n=[];for(let r of s){let a=this.messages.get(r);a&&n.push(a);}return n.sort((r,a)=>r.createdAt-a.createdAt),n.slice(-t)}getPendingMessages(e){let t=[];for(let s of this.messages.values())s.status==="pending"&&(!e||s.message.sessionId===e)&&t.push(s);return t}getFailedMessages(e=3){let t=[];for(let s of this.messages.values())s.status==="failed"&&s.retryCount<e&&t.push(s);return t}async cleanup(){let e=Date.now(),t=this.config.maxRetentionDays*24*60*60*1e3,s=[];for(let[n,r]of this.messages)e-r.createdAt>t&&s.push(n);for(let n of s){let r=this.messages.get(n);if(r){let a=this.sessionMessages.get(r.message.sessionId);a&&a.delete(n),this.messages.delete(n);}}return s.length>0&&this.log.info("cleaned up expired messages",{count:s.length}),s.length}getStats(){let e={total:this.messages.size,pending:0,processing:0,completed:0,failed:0,cancelled:0};for(let t of this.messages.values())e[t.status]++;return e}};a();var M=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:session-store"}));e(this,"config");e(this,"sessions",new Map);e(this,"channelSessions",new Map);e(this,"autoSaveTimer",null);e(this,"isDirty",false);this.config={storagePath:e$1.storagePath??"./data/gateway-sessions",autoSaveInterval:e$1.autoSaveInterval??6e4,maxRetentionDays:e$1.maxRetentionDays??7,enablePersistence:e$1.enablePersistence??true};}async initialize(){if(!this.config.enablePersistence){this.log.info("session persistence disabled");return}await this.ensureStorageDir(),await this.load(),this.startAutoSave(),this.log.info("session store initialized",{sessionCount:this.sessions.size,storagePath:this.config.storagePath});}async close(){this.stopAutoSave(),this.isDirty&&await this.save(),this.log.info("session store closed");}async set(e){this.sessions.set(e.id,e),this.channelSessions.has(e.channel.channelId)||this.channelSessions.set(e.channel.channelId,new Set),this.channelSessions.get(e.channel.channelId).add(e.id),this.markDirty();}get(e){return this.sessions.get(e)}async delete(e){let t=this.sessions.get(e);if(!t)return;this.sessions.delete(e);let s=this.channelSessions.get(t.channel.channelId);s&&(s.delete(e),s.size===0&&this.channelSessions.delete(t.channel.channelId)),this.markDirty();}getAll(){return [...this.sessions.values()]}getByChannel(e){let t=this.channelSessions.get(e);return t?[...t].map(s=>this.sessions.get(s)).filter(s=>s!==void 0):[]}size(){return this.sessions.size}markDirty(){this.isDirty=true;}async save(){if(!this.config.enablePersistence)return;let e=this.getSessionFilePath(),t=this.serializeAll();try{await this.ensureStorageDir(),await m.promises.writeFile(e,JSON.stringify(t,null,2),"utf-8"),this.isDirty=!1,this.log.debug("sessions saved",{count:t.length});}catch(s){throw this.log.error("failed to save sessions",{error:s}),s}}async load(){if(!this.config.enablePersistence)return;let e=this.getSessionFilePath();try{if(!m.existsSync(e)){this.log.debug("no saved sessions found");return}let t=await m.promises.readFile(e,"utf-8"),s=JSON.parse(t);this.sessions.clear(),this.channelSessions.clear();let n=Date.now(),r=this.config.maxRetentionDays*24*60*60*1e3;for(let a of s){if(n-a.lastActiveAt>r)continue;let g={id:a.id,channel:a.channel,backendSessionId:a.backendSessionId,subscribers:new Set(a.subscribers),state:a.state,createdAt:a.createdAt,lastActiveAt:a.lastActiveAt};this.sessions.set(g.id,g),this.channelSessions.has(g.channel.channelId)||this.channelSessions.set(g.channel.channelId,new Set),this.channelSessions.get(g.channel.channelId).add(g.id);}this.log.info("sessions loaded",{loaded:this.sessions.size,skipped:s.length-this.sessions.size});}catch(t){this.log.error("failed to load sessions",{error:t});}}serializeAll(){let e=[];for(let t of this.sessions.values())e.push(this.serialize(t));return e}serialize(e){return {id:e.id,channel:e.channel,backendSessionId:e.backendSessionId,subscribers:[...e.subscribers],state:e.state,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt}}getSessionFilePath(){return z.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){m.existsSync(this.config.storagePath)||await m.promises.mkdir(this.config.storagePath,{recursive:true});}startAutoSave(){this.autoSaveTimer||(this.autoSaveTimer=setInterval(async()=>{this.isDirty&&await this.save();},this.config.autoSaveInterval));}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null);}async cleanup(){let e=Date.now(),t=this.config.maxRetentionDays*24*60*60*1e3,s=[];for(let n of this.sessions.values())e-n.lastActiveAt>t&&s.push(n.id);for(let n of s)await this.delete(n);return s.length>0&&(this.log.info("cleaned up expired sessions",{count:s.length}),await this.save()),s.length}getStats(){let e={total:this.sessions.size,byStatus:{active:0,idle:0,closed:0},byPlatform:{}};for(let t of this.sessions.values()){e.byStatus[t.state.status]++;let s=t.channel.platform;e.byPlatform[s]=(e.byPlatform[s]||0)+1;}return e}};var w=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:session"}));e(this,"sessionStore");e(this,"config");e(this,"initialized",false);this.config={enablePersistence:e$1.enablePersistence??true,storagePath:e$1.storagePath??"./data/gateway-sessions",autoSaveInterval:e$1.autoSaveInterval??6e4,maxRetentionDays:e$1.maxRetentionDays??7},this.sessionStore=new M({storagePath:this.config.storagePath,autoSaveInterval:this.config.autoSaveInterval,maxRetentionDays:this.config.maxRetentionDays,enablePersistence:this.config.enablePersistence});}async initialize(){this.initialized||(await this.sessionStore.initialize(),this.initialized=true,this.log.info("session manager initialized",{sessionCount:this.sessionStore.size(),persistenceEnabled:this.config.enablePersistence}));}async close(){await this.sessionStore.close(),this.log.info("session manager closed");}async getOrCreate(e,t={}){let s=E(e),n=this.sessionStore.get(s);return n?(n.lastActiveAt=Date.now(),this.log.debug("session found",{sessionId:s}),n):(n={id:s,channel:e,backendSessionId:null,subscribers:new Set,state:D(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(n),this.log.info("session created",{sessionId:s,platform:e.platform,channelId:e.channelId,chatId:e.chatId,userId:e.userId}),n)}get(e){return this.sessionStore.get(e)}async closeSession(e){let t=this.sessionStore.get(e);if(!t){this.log.warn("session not found",{sessionId:e});return}t.state.status="closed",await this.sessionStore.delete(e),this.log.info("session closed",{sessionId:e});}async closeById(e){return this.closeSession(e)}async bindBackendSession(e,t){let s=this.sessionStore.get(e);if(!s)throw new Error(`Session not found: ${e}`);s.backendSessionId=t,await this.sessionStore.set(s),this.log.info("backend session bound",{gatewaySessionId:e,backendSessionId:t});}async unbindBackendSession(e){let t=this.sessionStore.get(e);if(!t){this.log.warn("session not found",{sessionId:e});return}t.backendSessionId=null,await this.sessionStore.set(t),this.log.info("backend session unbound",{gatewaySessionId:e});}getState(e){return this.sessionStore.get(e)?.state}async incrementMessageCountOrCreate(e,t){let s=this.sessionStore.get(e);if(!s){let n=t??{platform:"api",channelId:"default"};s=await this.getOrCreate(n);}return s.state.messageCount++,s.state.lastMessageAt=Date.now(),s.lastActiveAt=Date.now(),await this.sessionStore.set(s),s}async incrementMessageCount(e){let t=this.sessionStore.get(e);t&&(t.state.messageCount++,t.state.lastMessageAt=Date.now(),t.lastActiveAt=Date.now(),await this.sessionStore.set(t));}async addSubscriber(e,t){let s=this.sessionStore.get(e);if(!s){this.log.warn("session not found",{sessionId:e});return}s.subscribers.add(t),await this.sessionStore.set(s),this.log.debug("subscriber added to session",{sessionId:e,subscriberId:t});}async removeSubscriber(e,t){let s=this.sessionStore.get(e);s&&(s.subscribers.delete(t),await this.sessionStore.set(s),this.log.debug("subscriber removed from session",{sessionId:e,subscriberId:t}));}query(e){let t=this.sessionStore.getAll();return e.platform&&(t=t.filter(s=>s.channel.platform===e.platform)),e.channelId&&(t=t.filter(s=>s.channel.channelId===e.channelId)),e.userId&&(t=t.filter(s=>s.channel.userId===e.userId)),e.status&&(t=t.filter(s=>s.state.status===e.status)),t}getSessionsByChannel(e){return this.sessionStore.getByChannel(e)}getAllSessions(){return this.sessionStore.getAll()}getSessionCount(){return this.sessionStore.size()}async cleanupIdleSessions(e){let t=Date.now(),s=[];for(let n of this.sessionStore.getAll())n.state.status==="idle"&&t-n.lastActiveAt>e&&s.push(n.id);for(let n of s)await this.closeSession(n);return s.length>0&&this.log.info("cleaned up idle sessions",{count:s.length}),s.length}async save(){this.log.debug("session save triggered");}getStats(){return this.sessionStore.getStats()}};a();var I=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:plugin-loader"}));e(this,"plugins",new Map);e(this,"messageHandler",null);e(this,"healthCheckTimer",null);e(this,"config");this.config={pluginDir:e$1.pluginDir??"./plugins",autoDiscover:e$1.autoDiscover??false,healthCheckInterval:e$1.healthCheckInterval??6e4,healthCheckTimeout:e$1.healthCheckTimeout??5e3};}setMessageHandler(e){this.messageHandler=e;}async register(e,t){if(this.plugins.has(e.id)){this.log.warn("plugin already registered",{id:e.id});return}this.plugins.set(e.id,{plugin:e,config:t,started:false}),this.log.info("plugin registered",{id:e.id,platform:e.platform,name:e.name});}async unregister(e){let t=this.plugins.get(e);if(!t){this.log.warn("plugin not found",{id:e});return}t.started&&await this.stop(e),this.plugins.delete(e),this.log.info("plugin unregistered",{id:e});}async start(e){let t=this.plugins.get(e);if(!t)throw new Error(`Plugin not found: ${e}`);if(t.started){this.log.warn("plugin already started",{id:e});return}if(!this.messageHandler)throw new Error("Message handler not set");if(!t.config.enabled){this.log.warn("plugin is disabled",{id:e});return}this.log.info("starting plugin",{id:e});try{await t.plugin.start(t.config,this.messageHandler),t.started=!0,this.log.info("plugin started",{id:e});}catch(s){throw this.log.error("failed to start plugin",{id:e,error:String(s)}),s}}async stop(e){let t=this.plugins.get(e);if(!t){this.log.warn("plugin not found",{id:e});return}if(!t.started){this.log.warn("plugin not started",{id:e});return}this.log.info("stopping plugin",{id:e});try{await t.plugin.stop(),t.started=!1,this.log.info("plugin stopped",{id:e});}catch(s){throw this.log.error("failed to stop plugin",{id:e,error:String(s)}),s}}async startAll(){let e=[];for(let[t,s]of this.plugins){if(!s.config.enabled){this.log.debug("skipping disabled plugin",{id:t});continue}try{await this.start(t);}catch(n){e.push({id:t,error:n instanceof Error?n:new Error(String(n))});}}e.length>0&&this.log.warn("some plugins failed to start",{count:e.length,errors:e.map(t=>({id:t.id,error:t.error.message}))});}async stopAll(){let e=[];for(let[t,s]of this.plugins)if(s.started)try{await this.stop(t);}catch(n){e.push({id:t,error:n instanceof Error?n:new Error(String(n))});}e.length>0&&this.log.warn("some plugins failed to stop",{count:e.length,errors:e.map(t=>({id:t.id,error:t.error.message}))});}getPlugin(e){return this.plugins.get(e)?.plugin}getAllPlugins(){return [...this.plugins.values()].map(e=>e.plugin)}getRunningPlugins(){return [...this.plugins.values()].filter(e=>e.started).map(e=>e.plugin)}isRunning(e){return this.plugins.get(e)?.started??false}async healthCheck(e){let t=this.plugins.get(e);if(!t)return {healthy:false,lastCheck:Date.now(),error:"Plugin not found"};try{let s=await Promise.race([t.plugin.healthCheck(),new Promise((n,r)=>setTimeout(()=>r(new Error("Health check timeout")),this.config.healthCheckTimeout))]);return t.lastHealthCheck=s,s}catch(s){let n={healthy:false,lastCheck:Date.now(),error:s instanceof Error?s.message:String(s)};return t.lastHealthCheck=n,n}}async healthCheckAll(){let e=new Map;for(let[t]of this.plugins)e.set(t,await this.healthCheck(t));return e}startHealthCheckTimer(){if(this.healthCheckTimer){this.log.warn("health check timer already running");return}this.healthCheckTimer=setInterval(async()=>{let e=await this.healthCheckAll();for(let[t,s]of e)s.healthy||this.log.warn("plugin health check failed",{id:t,error:s.error});},this.config.healthCheckInterval),this.log.info("health check timer started",{interval:this.config.healthCheckInterval});}stopHealthCheckTimer(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null,this.log.info("health check timer stopped"));}async sendToPlugin(e,t){let s=this.plugins.get(e);if(!s)throw new Error(`Plugin not found: ${e}`);if(!s.started)throw new Error(`Plugin not started: ${e}`);return s.plugin.send(t)}};a();var l=a$1.create({service:"gateway:websocket-server"});function J(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function R(c,e){for(let[t,s]of e.entries())if(s===c)return t;return null}var G=class{constructor(e$1={}){e(this,"config");e(this,"server",null);e(this,"wss",null);e(this,"httpsServer",null);e(this,"httpRedirectServer",null);e(this,"connections",new Map);e(this,"subscriptions",new Map);e(this,"sessionSubscriptions",new Map);e(this,"sessionLastActivity",new Map);e(this,"cleanupInterval",null);e(this,"heartbeatInterval",null);e(this,"startTime",0);e(this,"running",false);this.config={..._,...e$1};}async start(){if(this.running){l.warn("WebSocket server is already running");return}l.info("Starting WebSocket server",{port:this.config.port,hostname:this.config.hostname,path:this.config.path,https:this.config.https?.enabled??false}),this.startTime=Date.now();let e={onOpen:(s,n)=>{this.handleConnection(n);},onMessage:async(s,n)=>{try{let r=JSON.parse(s.data.toString());await this.handleMessage(n,r);}catch(r){l.error("Error processing WebSocket message",{error:r.message}),this.sendError(n,r.message);}},onClose:(s,n)=>{this.handleDisconnection(n);},onError:(s,n)=>{l.error("WebSocket error",{error:s.type});}};this.config.https?.enabled?await this.startHTTPSServer(e):await this.startHTTPServer(e),this.cleanupInterval=setInterval(()=>this.cleanupExpiredSessions(),3e4),this.heartbeatInterval=setInterval(()=>this.checkConnectionTimeout(),this.config.heartbeatInterval),this.running=true;let t=this.config.https?.enabled?"wss":"ws";l.info("WebSocket server started",{url:`${t}://${this.config.hostname}:${this.config.port}${this.config.path}`});}async startHTTPServer(e){this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true});let t=this.server.raw;t&&this.setupWebSocketUpgrade(t,e);}async startHTTPSServer(e){let t=this.config.https,s=this.loadSSLCertificates(t);if(!s){l.error("Failed to load SSL certificates, falling back to HTTP"),await this.startHTTPServer(e);return}this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true});let n=this.server.raw;this.httpsServer=V.createServer(s,n.listeners("request")[0]),this.setupWebSocketUpgrade(this.httpsServer,e),await new Promise(r=>{this.httpsServer.listen(this.config.port,this.config.hostname,()=>{l.info("HTTPS server started",{port:this.config.port,hostname:this.config.hostname}),r();});}),t.forceRedirect&&t.httpPort&&this.startHTTPRedirectServer(t.httpPort);}loadSSLCertificates(e){try{return e.cert&&e.key?{cert:e.cert,key:e.key}:e.certPath&&e.keyPath?{cert:m__default.readFileSync(e.certPath),key:m__default.readFileSync(e.keyPath)}:null}catch(t){return l.error("Failed to load SSL certificates",{error:t.message}),null}}setupWebSocketUpgrade(e,t){this.wss=new WebSocketServer({noServer:true}),e.on("upgrade",(s,n,r)=>{try{let g=new URL(s.url||"/",`http://${s.headers.host}`).pathname;(g===this.config.path||this.config.path==="/"&&(g==="/"||g===""))&&this.wss.handleUpgrade(s,n,r,u=>{t.onOpen?.({type:"open"},u),u.on("message",f=>{t.onMessage?.({data:f},u);}),u.on("close",(f,L)=>{t.onClose?.({code:f,reason:L},u);}),u.on("error",f=>{t.onError?.({type:"error",message:f.message},u);});});}catch{}});}startHTTPRedirectServer(e){this.httpRedirectServer=K.createServer((t,s)=>{let r=`https://${t.headers.host?.split(":")[0]||this.config.hostname}:${this.config.port}${t.url}`;l.debug("Redirecting HTTP to HTTPS",{from:t.url,to:r}),s.writeHead(301,{Location:r,"Content-Type":"text/plain"}),s.end(`Redirecting to ${r}`);}),this.httpRedirectServer.listen(e,this.config.hostname,()=>{l.info("HTTP redirect server started",{port:e,hostname:this.config.hostname});});}async stop(){if(!this.running){l.warn("WebSocket server is not running");return}l.info("Stopping WebSocket server"),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let[e,t]of this.connections.entries())try{t.close(1e3,"Server shutting down");}catch(s){l.debug("Error closing connection",{clientId:e,error:String(s)});}this.connections.clear(),this.subscriptions.clear(),this.sessionSubscriptions.clear(),this.sessionLastActivity.clear(),this.wss&&(this.wss.close(),this.wss=null),this.httpsServer&&(await new Promise(e=>{this.httpsServer.close(()=>e());}),this.httpsServer=null),this.httpRedirectServer&&(await new Promise(e=>{this.httpRedirectServer.close(()=>e());}),this.httpRedirectServer=null),this.server&&(await this.server.stop(),this.server=null),this.running=false,l.info("WebSocket server stopped");}broadcastToSession(e,t){this.touchSession(e);let s=this.sessionSubscriptions.get(e);if(!s||s.size===0){l.debug("No clients subscribed to session",{sessionId:e});return}let n=t?.properties?.sessionID;if(typeof n=="string"&&n&&n!==e)return;let r=JSON.stringify({type:"event",sessionId:e,payload:t});for(let a of s){let g=this.subscriptions.get(a);if(g&&g.ws.readyState===g.ws.OPEN&&g.subscribedSessions.has(e)){if(g.subscribedEventTypes.size>0&&!g.subscribedEventTypes.has(t.type)){l.debug("Event type not subscribed, skipping",{clientId:a,sessionId:e,eventType:t.type,subscribedTypes:Array.from(g.subscribedEventTypes)});continue}g.ws.send(r),l.debug("Event pushed to client",{clientId:a,sessionId:e,eventType:t.type});}}}getConnectionCount(){return this.connections.size}getSubscriptionCount(){return this.sessionSubscriptions.size}getConnectionInfos(){let e=[];for(let[t,s]of this.subscriptions.entries())e.push({clientId:t,state:s.ws.readyState===s.ws.OPEN?"connected":"disconnected",connectedAt:s.connectedAt,lastActivityAt:s.lastActivityAt,authInfo:s.authInfo});return e}isRunning(){return this.running}handleConnection(e){if(this.connections.size>=(this.config.maxConnections??v.maxConnections)){l.warn("Maximum connections reached, rejecting new connection"),e.close(1013,"Maximum connections reached");return}let t=J();this.connections.set(t,e),this.subscriptions.set(t,{clientId:t,ws:e,subscribedSessions:new Set,subscribedEventTypes:new Set,connectedAt:Date.now(),lastActivityAt:Date.now()}),l.info("WebSocket client connected",{clientId:t,totalConnections:this.connections.size}),this.sendMessage(e,{type:"connected",clientId:t,payload:{version:"1.0.0",capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}handleDisconnection(e){let t=R(e,this.connections);if(!t)return;this.connections.delete(t);let s=this.subscriptions.get(t);if(s){for(let n of s.subscribedSessions){let r=this.sessionSubscriptions.get(n);r&&(r.delete(t),r.size===0&&this.sessionSubscriptions.delete(n));}this.subscriptions.delete(t);}l.info("WebSocket client disconnected",{clientId:t,totalConnections:this.connections.size});}async handleMessage(e,t){let s=R(e,this.connections);if(!s){this.sendError(e,"Client not found");return}let n=this.subscriptions.get(s);switch(n&&(n.lastActivityAt=Date.now()),t.type){case "ping":this.sendMessage(e,{type:"pong"});break;case "initialize":await this.handleInitialize(e,t);break;case "subscribe":await this.handleSubscribe(e,t);break;case "unsubscribe":await this.handleUnsubscribe(e,t);break;case "message":await this.handleMessageRequest(e,t);break;case "interrupt":await this.handleInterrupt(e,t);break;case "releaseSubscription":await this.handleReleaseSubscription(e,t);break;default:this.sendError(e,`Unknown message type: ${t.type}`);}}async handleInitialize(e,t){this.sendMessage(e,{type:"initialize_response",success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}async handleSubscribe(e,t){if(t.type!=="subscribe"||!t.sessionId){this.sendError(e,"Invalid subscribe request");return}let s=R(e,this.connections);if(!s){this.sendError(e,"Client not found");return}let n=this.subscriptions.get(s);if(!n){this.sendError(e,"Subscription not found");return}if(n.subscribedSessions.add(t.sessionId),this.sessionSubscriptions.has(t.sessionId)||this.sessionSubscriptions.set(t.sessionId,new Set),this.sessionSubscriptions.get(t.sessionId).add(s),this.touchSession(t.sessionId),t.payload?.eventTypes)for(let r of t.payload.eventTypes)n.subscribedEventTypes.add(r);l.info("Client subscribed to session",{clientId:s,sessionId:t.sessionId}),this.sendMessage(e,{type:"subscribed",sessionId:t.sessionId});}async handleUnsubscribe(e,t){if(t.type!=="unsubscribe"||!t.sessionId){this.sendError(e,"Invalid unsubscribe request");return}let s=R(e,this.connections);if(!s)return;let n=this.subscriptions.get(s);if(!n)return;n.subscribedSessions.delete(t.sessionId);let r=this.sessionSubscriptions.get(t.sessionId);r&&(r.delete(s),r.size===0&&this.sessionSubscriptions.delete(t.sessionId)),l.info("Client unsubscribed from session",{clientId:s,sessionId:t.sessionId}),this.sendMessage(e,{type:"unsubscribed",sessionId:t.sessionId});}async handleMessageRequest(e,t){if(t.type!=="message"||!t.sessionId||!t.payload){this.sendError(e,"Invalid message request");return}l.debug("Message received",{sessionId:t.sessionId}),this.sendMessage(e,{type:"response",sessionId:t.sessionId,success:true,result:{received:true}});}async handleInterrupt(e,t){if(t.type!=="interrupt"||!t.sessionId){this.sendError(e,"Invalid interrupt request");return}l.info("Interrupt requested via WebSocket",{sessionId:t.sessionId}),this.sendMessage(e,{type:"interrupted",sessionId:t.sessionId,success:true});}async handleReleaseSubscription(e,t){if(t.type!=="releaseSubscription"||!t.sessionId){this.sendError(e,"Invalid releaseSubscription request");return}l.info("Release subscription requested via WebSocket",{sessionId:t.sessionId}),this.releaseSessionResources(t.sessionId),this.sendMessage(e,{type:"subscriptionReleased",sessionId:t.sessionId});}touchSession(e){this.sessionLastActivity.set(e,Date.now());}checkConnectionTimeout(){let e=Date.now(),t=this.config.connectionTimeout??v.connectionTimeout,s=[];for(let[n,r]of this.subscriptions.entries())e-r.lastActivityAt>t&&s.push(n);for(let n of s){let r=this.subscriptions.get(n);if(r){l.info("Closing inactive connection",{clientId:n,lastActivityAt:r.lastActivityAt,timeoutMs:t});try{r.ws.close(1001,"Connection timeout");}catch(a){l.debug("Error closing timed out connection",{clientId:n,error:String(a)});}}}s.length>0&&l.debug("Closed timed out connections",{count:s.length,remainingConnections:this.connections.size-s.length});}cleanupExpiredSessions(){let e=Date.now(),t=[],s=this.config.sessionExpireMs??v.sessionExpireMs;for(let[n,r]of this.sessionLastActivity.entries())e-r>s&&t.push(n);for(let n of t)l.info("Session expired due to inactivity, releasing resources",{sessionId:n,lastActivity:this.sessionLastActivity.get(n),expireMs:s}),this.releaseSessionResources(n),this.sessionLastActivity.delete(n);t.length>0&&l.debug("Cleaned up expired sessions",{count:t.length,remainingActive:this.sessionLastActivity.size});}releaseSessionResources(e){let t=this.sessionSubscriptions.get(e);if(t){for(let s of t){let n=this.subscriptions.get(s);n&&n.ws.readyState===n.ws.OPEN&&this.sendMessage(n.ws,{type:"session_closed",sessionId:e,payload:{reason:"Session resources released due to expiration or explicit release"}});}for(let s of t){let n=this.subscriptions.get(s);n&&n.subscribedSessions.delete(e);}this.sessionSubscriptions.delete(e),l.info("Session resources released",{sessionId:e,clientCount:t.size});}}sendMessage(e,t){e.readyState===e.OPEN&&e.send(JSON.stringify(t));}sendError(e,t,s){this.sendMessage(e,{type:"error",message:t,code:s});}createRoutes(){return [{method:"get",path:"/health",handler:e=>{let t={status:"healthy",timestamp:Date.now(),version:"1.0.0"};return e.json(t)}},{method:"get",path:"/status",handler:e=>{let t={status:this.running?"running":"stopped",connections:this.connections.size,sessions:this.sessionSubscriptions.size,subscriptions:this.subscriptions.size,uptime:this.running?Date.now()-this.startTime:0,version:"1.0.0"};return e.json(t)}},{method:"post",path:"/initialize",handler:async e=>{let t=await e.req.json().catch(()=>({}));return l.debug("ACP initialize request received",{body:t}),e.json({success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"],version:"1.0.0"}})}},{method:"post",path:"/session",handler:async e=>{await e.req.json().catch(()=>({}));let n={id:`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,createdAt:Date.now()};return e.json(n)}},{method:"post",path:"/session/:sessionId/prompt",handler:async e=>{let t=e.req.param("sessionId");await e.req.json().catch(()=>({}));if(!t)return e.json({error:"No sessionId provided"},400);let r={messageId:`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,sessionId:t,createdAt:Date.now()};return e.status(202),e.json(r)}},{method:"get",path:"/subscriptions",handler:e=>{let t=Array.from(this.sessionSubscriptions.entries()).map(([n,r])=>({sessionId:n,subscriberCount:r.size,subscribers:Array.from(r)})),s={subscriptions:t,total:t.length};return e.json(s)}}]}};function Y(c){let e={platform:c.channel?.platform??"api",channelId:c.channel?.channelId??"unknown",chatId:c.channel?.chatId,userId:c.channel?.userId};return {id:c.messageId??`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:c.sessionId,type:c.type,content:Array.isArray(c.content)?c.content:[{type:"text",text:String(c.content??"")}],metadata:{channel:e,replyToMessageId:c.replyToMessageId},timestamp:c.timestamp??Date.now()}}var B=class{constructor(e$1){e(this,"log",a$1.create({service:"gateway:server"}));e(this,"config");e(this,"router");e(this,"sessionManager");e(this,"pluginLoader");e(this,"messageStore");e(this,"running",false);e(this,"connections",0);this.config=e$1,this.router=new P,this.sessionManager=new w,this.pluginLoader=new I({healthCheckInterval:6e4});let t=R$1(),s=O();this.messageStore=new C({storagePath:`${t.Path.data}/gateway-messages`}),s&&P$1().setMessageStorage({store:async r=>{let a=Y(r);await this.messageStore.store(a);},updateStatus:async(r,a,g)=>{await this.messageStore.updateStatus(r,a,g);}}),this.pluginLoader.setMessageHandler({onMessage:n=>this.onMessage(n),onEvent:n=>this.onEvent(n)});}async start(){if(this.running){this.log.warn("gateway server is already running");return}this.log.info("starting gateway server",{port:this.config.port,hostname:this.config.hostname}),await this.sessionManager.initialize(),await this.pluginLoader.startAll(),this.pluginLoader.startHealthCheckTimer(),this.running=true,this.log.info("gateway server started");}async stop(){if(!this.running){this.log.warn("gateway server is not running");return}this.log.info("stopping gateway server"),this.pluginLoader.stopHealthCheckTimer(),await this.pluginLoader.stopAll(),await this.router.shutdown(),await this.sessionManager.close(),this.running=false,this.log.info("gateway server stopped");}getStatus(){return {running:this.running,port:this.config.port,hostname:this.config.hostname,connections:this.connections}}async onMessage(e){if(this.log.debug("message received",{id:e.id,sessionId:e.sessionId,type:e.type}),this.messageStore.isProcessed(e.id)){this.log.warn("message already processed, skipping",{id:e.id});return}await this.storeMessage(e),await this.sessionManager.incrementMessageCountOrCreate(e.sessionId,e.metadata.channel),(await this.router.route(e)).broadcastCount===0&&e.type==="input"&&this.log.debug("no subscribers, message pending",{id:e.id});}async storeMessage(e){if(await this.messageStore.store(e),O())try{let t=P$1(),s={name:HookEvent.GatewayMessageReceive,data:{messageId:e.id,sessionId:e.sessionId,type:e.type,content:e.content,channel:e.metadata.channel,replyToMessageId:e.metadata.replyToMessageId,timestamp:e.timestamp||Date.now()}};await t.hookRegistry.emit(s);}catch{this.log.debug("hook trigger skipped (no context)");}}async processMessage(e,t,s,n={}){if(await this.messageStore.updateStatus(t,"processing",{processedBy:s}),O())try{await P$1().hookRegistry.emit({name:HookEvent.GatewayMessageProcess,data:{messageId:t,sessionId:e,processorId:s,processType:n.processType||"direct",agent:n.agent,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}}async completeMessage(e,t,s,n={}){let{success:r=true,error:a,responseMessageId:g,tokens:u,duration:f}=n;if(await this.messageStore.updateStatus(t,r?"completed":"failed",{processedBy:s,error:a}),O())try{await P$1().hookRegistry.emit({name:HookEvent.GatewayMessageComplete,data:{messageId:t,sessionId:e,processorId:s,status:r?"completed":"failed",error:a,responseMessageId:g,tokens:u,duration:f,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}await this.router.completeMessage(e,t,s,r?"completed":"failed");}async onEvent(e){switch(this.log.debug("channel event",{type:e.type,channelId:e.channelId}),e.type){case "connected":this.connections++;break;case "disconnected":this.connections--;break;case "error":this.log.error("channel error",{channelId:e.channelId,data:e.data});break}}async registerChannel(e,t){let s=t??{enabled:true,platform:{},session:{autoCreate:true,resetPolicy:"onNewConversation"},routing:{broadcast:true,dispatchToSubAgent:false}};await this.pluginLoader.register(e,s),this.running&&await this.pluginLoader.start(e.id);}async unregisterChannel(e){await this.pluginLoader.unregister(e);}async subscribe(e,t){await this.router.subscribe(e,t),await this.sessionManager.addSubscriber(e,t.id);}async unsubscribe(e){await this.router.unsubscribe(e);}async send(e){await this.onMessage(e);}async sendToChannel(e,t,s={}){let{proactive:n=false,replyToMessageId:r}=s;if(O())try{await P$1().hookRegistry.emit({name:HookEvent.GatewayMessageSend,data:{messageId:t.id,sessionId:t.sessionId,type:t.type,channel:t.metadata.channel,proactive:n,replyToMessageId:r,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}return this.pluginLoader.sendToPlugin(e,t)}async sendProactiveMessage(e,t,s,n){let r={id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:t,type:"output",content:s,metadata:{channel:n},timestamp:Date.now()};return this.sendToChannel(e,r,{proactive:true})}getSessionManager(){return this.sessionManager}getRouter(){return this.router}getPluginLoader(){return this.pluginLoader}getMessageStore(){return this.messageStore}async getMessageHistory(e,t){return this.messageStore.getSessionHistory(e,t)}};
|
|
1
|
+
import {w as w$1,a as a$1,R as R$1,O,P as P$1}from'./chunk-ETYFY7SI.mjs';import {a}from'./chunk-SJNPXLNN.mjs';import {e}from'./chunk-TY6W6O7O.mjs';import*as m from'fs';import m__default from'fs';import*as z from'path';import {HookEvent}from'@easbot/plugin';import {createServer}from'@easbot/utils';import {WebSocketServer}from'ws';import V from'https';import K from'http';a();a();a();var x=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:lock"}));e(this,"config");e(this,"locks",new Map);e(this,"cleanupTimer",null);this.config={defaultTimeout:e$1.defaultTimeout??6e4,checkInterval:e$1.checkInterval??1e4};}tryAcquire(e,t,s,n){let r=this.locks.get(e);if(r)if(this.isLockExpired(r))this.log.warn("lock expired, releasing",{sessionId:e,oldHolder:r.holderId,newHolder:s}),this.locks.delete(e);else return this.log.debug("lock already held",{sessionId:e,holder:r.holderId,messageId:r.messageId}),false;let a={sessionId:e,messageId:t,holderId:s,acquiredAt:Date.now(),timeout:n??this.config.defaultTimeout};return this.locks.set(e,a),this.log.debug("lock acquired",{sessionId:e,messageId:t,subscriberId:s}),true}release(e,t){let s=this.locks.get(e);return s?s.holderId!==t?(this.log.warn("cannot release lock held by another",{sessionId:e,holder:s.holderId,requester:t}),false):(this.locks.delete(e),this.log.debug("lock released",{sessionId:e,subscriberId:t}),true):(this.log.debug("no lock to release",{sessionId:e}),false)}forceRelease(e){let t=this.locks.get(e);return t?(this.locks.delete(e),this.log.warn("lock force released",{sessionId:e,holder:t.holderId,messageId:t.messageId}),true):false}isLockExpired(e){return Date.now()-e.acquiredAt>e.timeout}getLock(e){return this.locks.get(e)}isLocked(e){let t=this.locks.get(e);return t?this.isLockExpired(t)?(this.locks.delete(e),false):true:false}getHolder(e){let t=this.locks.get(e);if(!(!t||this.isLockExpired(t)))return t.holderId}startCleanup(){this.cleanupTimer||(this.cleanupTimer=setInterval(()=>{this.cleanupExpired();},this.config.checkInterval),this.log.info("lock cleanup started",{interval:this.config.checkInterval}));}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null,this.log.info("lock cleanup stopped"));}cleanupExpired(){let e=0;for(let[t,s]of this.locks)this.isLockExpired(s)&&(this.locks.delete(t),e++,this.log.warn("expired lock cleaned up",{sessionId:t,holder:s.holderId,messageId:s.messageId}));return e>0&&this.log.info("cleaned up expired locks",{count:e}),e}getAllLocks(){return [...this.locks.values()]}getLockCount(){return this.locks.size}};a();var k=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:retry"}));e(this,"policy");e(this,"retryQueue",new Map);e(this,"retryTimer",null);e(this,"handlers",new Map);this.policy={maxRetries:e$1.maxRetries??3,initialDelay:e$1.initialDelay??1e3,maxDelay:e$1.maxDelay??3e4,backoffMultiplier:e$1.backoffMultiplier??2};}registerHandler(e,t){this.handlers.set(e,t);}unregisterHandler(e){this.handlers.delete(e);}scheduleRetry(e,t){let s=e.id,n=this.retryQueue.get(s);if(n||(n={messageId:s,retryCount:0,nextRetryAt:0,errors:[]},this.retryQueue.set(s,n)),n.errors.push({error:t.message,timestamp:Date.now()}),n.retryCount>=this.policy.maxRetries)return this.log.error("max retries exceeded",{messageId:s,retryCount:n.retryCount,maxRetries:this.policy.maxRetries}),false;let r=Math.min(this.policy.initialDelay*this.policy.backoffMultiplier**n.retryCount,this.policy.maxDelay);return n.retryCount++,n.nextRetryAt=Date.now()+r,this.log.warn("retry scheduled",{messageId:s,retryCount:n.retryCount,delay:r,error:t.message}),true}getPendingRetries(){let e=Date.now(),t=[];for(let s of this.retryQueue.values())s.nextRetryAt<=e&&s.retryCount<=this.policy.maxRetries&&t.push(s);return t}async executeRetry(e){if(!this.handlers.get(e.messageId))return this.log.warn("no handler for retry",{messageId:e.messageId}),false;this.retryQueue.delete(e.messageId);try{return this.log.info("executing retry",{messageId:e.messageId,retryCount:e.retryCount}),!0}catch(s){return this.log.error("retry execution failed",{messageId:e.messageId,error:String(s)}),false}}clearRetry(e){this.retryQueue.delete(e),this.handlers.delete(e),this.log.debug("retry cleared",{messageId:e});}startProcessing(){this.retryTimer||(this.retryTimer=setInterval(async()=>{let e=this.getPendingRetries();for(let t of e)await this.executeRetry(t);},1e3),this.log.info("retry processing started"));}stopProcessing(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null,this.log.info("retry processing stopped"));}getStats(){let e=0;for(let t of this.retryQueue.values())e+=t.errors.length;return {pendingCount:this.retryQueue.size,totalErrors:e}}};a();a();function W(c,e,t,s){return {id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:c,type:e,content:t,metadata:{channel:{platform:s?.channel?.platform??"api",channelId:s?.channel?.channelId??"default",userId:s?.channel?.userId,chatId:s?.channel?.chatId,...Object.fromEntries(Object.entries(s?.channel??{}).filter(([n])=>!["platform","channelId","userId","chatId"].includes(n)))},context:s?.context,agent:s?.agent},timestamp:Date.now()}}function q(c,e,t,s){return W(c,e,[{type:"text",text:t}],s)}a();function E(c){let e=[c.platform,c.channelId];return c.chatId&&e.push(c.chatId),c.userId&&e.push(c.userId),e.join("_")}function D(){return {status:"active",messageCount:0,lastMessageAt:null}}a();function A(c,e){return `sub_${c}_${e}`}a();var _=w$1,v={maxConnections:w$1.maxConnections??1e3,connectionTimeout:w$1.connectionTimeout??6e4,sessionExpireMs:w$1.sessionExpireMs??3e5,heartbeatInterval:w$1.heartbeatInterval??3e4};a();var F={type:"token",enabled:true,tokens:[],onInvalid:"reject",allowAnonymous:false,defaultPermissions:[]};a();var U={heartbeatInterval:3e4,heartbeatTimeout:9e4,heartbeatCheckInterval:1e4,autoDeregisterTimeout:3e5,maxAgents:100,maxRegistrations:1e3};a();var $={mode:"both",interval:3e4,pushEvents:["register","deregister","status_change"],conflictResolution:"latest",remoteNodes:[]};a();var j={maxConnectionsPerChannel:100,idleTimeout:3e5,reuseStrategy:"lru",healthCheckInterval:6e4,acquireTimeout:5e3,warmupCount:0};var P=class{constructor(){e(this,"log",a$1.create({service:"gateway:router"}));e(this,"subscribers",new Map);e(this,"subscriptions",new Map);e(this,"sessionSubscriptions",new Map);e(this,"channelPlugins",new Map);e(this,"lockManager");e(this,"retryManager");e(this,"cancelHandlers",new Set);this.lockManager=new x,this.retryManager=new k,this.lockManager.startCleanup();}onCancel(e){this.cancelHandlers.add(e);}offCancel(e){this.cancelHandlers.delete(e);}async emitCancel(e){for(let t of this.cancelHandlers)try{await t(e);}catch(s){this.log.error("cancel handler error",{error:String(s)});}}async route(e){this.log.debug("routing message",{id:e.id,sessionId:e.sessionId,type:e.type});let t=this.sessionSubscriptions.get(e.sessionId);if(!t||t.size===0)return this.log.debug("no subscribers for session",{sessionId:e.sessionId}),{success:true,broadcastCount:0,dispatchedToSubAgent:false};let s=0,n=null,r=[];for(let a of t){let g=this.subscriptions.get(a);if(!g)continue;let u=this.subscribers.get(g.subscriberId);if(u){if(e.type==="input"){if(!this.lockManager.tryAcquire(e.sessionId,e.id,u.id)){this.log.debug("skipping subscriber, lock held by another",{subscriberId:u.id,holder:this.lockManager.getHolder(e.sessionId)});continue}n=u.id;}try{await u.connection.send(e),s++,u.lastActiveAt=Date.now();}catch(f){this.log.warn("failed to send message to subscriber",{subscriberId:u.id,error:String(f)}),r.push(f instanceof Error?f:new Error(String(f))),n===u.id&&(this.lockManager.release(e.sessionId,u.id),n=null);}}}return this.log.debug("message routed",{id:e.id,broadcastCount:s,errorCount:r.length,processedBy:n}),{success:r.length===0,broadcastCount:s,dispatchedToSubAgent:false,error:r.length>0?r.map(a=>a.message).join("; "):void 0}}async completeMessage(e,t,s,n="completed"){this.lockManager.release(e,s),await this.emitCancel({sessionId:e,messageId:t,processedBy:s,reason:n,timestamp:Date.now()}),this.log.info("message completed",{sessionId:e,messageId:t,subscriberId:s,reason:n});}scheduleRetry(e,t){return this.retryManager.scheduleRetry(e,t)}async subscribe(e,t){let s=A(t.id,e);if(this.subscriptions.has(s))return this.log.debug("already subscribed",{subscriberId:t.id,sessionId:e}),this.subscriptions.get(s);let n={id:s,subscriberId:t.id,sessionId:e,createdAt:Date.now()};return this.subscribers.has(t.id)||this.subscribers.set(t.id,t),this.subscriptions.set(s,n),this.sessionSubscriptions.has(e)||this.sessionSubscriptions.set(e,new Set),this.sessionSubscriptions.get(e).add(s),t.sessions.add(e),this.log.info("subscribed to session",{subscriberId:t.id,sessionId:e,subscriptionId:s}),n}async unsubscribe(e){let t=this.subscriptions.get(e);if(!t){this.log.warn("subscription not found",{subscriptionId:e});return}this.subscriptions.delete(e);let s=this.sessionSubscriptions.get(t.sessionId);s&&(s.delete(e),s.size===0&&this.sessionSubscriptions.delete(t.sessionId));let n=this.subscribers.get(t.subscriberId);n&&n.sessions.delete(t.sessionId),this.log.info("unsubscribed from session",{subscriberId:t.subscriberId,sessionId:t.sessionId,subscriptionId:e});}async unsubscribeAll(e){let t=this.subscribers.get(e);if(!t)return;let s=[...t.sessions];for(let n of s){let r=A(e,n);await this.unsubscribe(r);}this.subscribers.delete(e),this.log.info("unsubscribed all sessions",{subscriberId:e});}async registerChannel(e){if(this.channelPlugins.has(e.id)){this.log.warn("channel plugin already registered",{id:e.id});return}this.channelPlugins.set(e.id,e),this.log.info("channel plugin registered",{id:e.id,platform:e.platform});}async unregisterChannel(e){let t=this.channelPlugins.get(e);if(!t){this.log.warn("channel plugin not found",{id:e});return}await t.stop(),this.channelPlugins.delete(e),this.log.info("channel plugin unregistered",{id:e});}getSubscriberCount(e){let t=this.sessionSubscriptions.get(e);return t?t.size:0}getAllSubscribers(){return [...this.subscribers.values()]}getChannelPlugin(e){return this.channelPlugins.get(e)}getAllChannelPlugins(){return [...this.channelPlugins.values()]}getLockManager(){return this.lockManager}getRetryManager(){return this.retryManager}async shutdown(){this.lockManager.stopCleanup(),this.retryManager.stopProcessing(),this.log.info("router shutdown");}};a();a();a();a();var C=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:message-store"}));e(this,"config");e(this,"messages",new Map);e(this,"sessionMessages",new Map);this.config={storagePath:e$1.storagePath??"./data/gateway-messages",maxRetentionDays:e$1.maxRetentionDays??30,maxRecords:e$1.maxRecords??1e5};}async store(e){let t={message:e,status:"pending",processedBy:null,processedAt:null,retryCount:0,error:null,createdAt:Date.now(),updatedAt:Date.now()};return this.messages.set(e.id,t),this.sessionMessages.has(e.sessionId)||this.sessionMessages.set(e.sessionId,new Set),this.sessionMessages.get(e.sessionId).add(e.id),this.log.debug("message stored",{id:e.id,sessionId:e.sessionId,type:e.type}),t}get(e){return this.messages.get(e)}async updateStatus(e,t,s={}){let n=this.messages.get(e);if(!n){this.log.warn("message not found for status update",{messageId:e});return}n.status=t,n.updatedAt=Date.now(),s.processedBy&&(n.processedBy=s.processedBy),(t==="completed"||t==="failed")&&(n.processedAt=Date.now()),s.error&&(n.error=s.error),this.log.debug("message status updated",{id:e,status:t,processedBy:s.processedBy});}incrementRetry(e){let t=this.messages.get(e);return t?(t.retryCount++,t.updatedAt=Date.now(),t.retryCount):0}isProcessed(e){let t=this.messages.get(e);return t?t.status==="completed"||t.status==="processing":false}getSessionHistory(e,t=100){let s=this.sessionMessages.get(e);if(!s)return [];let n=[];for(let r of s){let a=this.messages.get(r);a&&n.push(a);}return n.sort((r,a)=>r.createdAt-a.createdAt),n.slice(-t)}getPendingMessages(e){let t=[];for(let s of this.messages.values())s.status==="pending"&&(!e||s.message.sessionId===e)&&t.push(s);return t}getFailedMessages(e=3){let t=[];for(let s of this.messages.values())s.status==="failed"&&s.retryCount<e&&t.push(s);return t}async cleanup(){let e=Date.now(),t=this.config.maxRetentionDays*24*60*60*1e3,s=[];for(let[n,r]of this.messages)e-r.createdAt>t&&s.push(n);for(let n of s){let r=this.messages.get(n);if(r){let a=this.sessionMessages.get(r.message.sessionId);a&&a.delete(n),this.messages.delete(n);}}return s.length>0&&this.log.info("cleaned up expired messages",{count:s.length}),s.length}getStats(){let e={total:this.messages.size,pending:0,processing:0,completed:0,failed:0,cancelled:0};for(let t of this.messages.values())e[t.status]++;return e}};a();var M=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:session-store"}));e(this,"config");e(this,"sessions",new Map);e(this,"channelSessions",new Map);e(this,"autoSaveTimer",null);e(this,"isDirty",false);this.config={storagePath:e$1.storagePath??"./data/gateway-sessions",autoSaveInterval:e$1.autoSaveInterval??6e4,maxRetentionDays:e$1.maxRetentionDays??7,enablePersistence:e$1.enablePersistence??true};}async initialize(){if(!this.config.enablePersistence){this.log.info("session persistence disabled");return}await this.ensureStorageDir(),await this.load(),this.startAutoSave(),this.log.info("session store initialized",{sessionCount:this.sessions.size,storagePath:this.config.storagePath});}async close(){this.stopAutoSave(),this.isDirty&&await this.save(),this.log.info("session store closed");}async set(e){this.sessions.set(e.id,e),this.channelSessions.has(e.channel.channelId)||this.channelSessions.set(e.channel.channelId,new Set),this.channelSessions.get(e.channel.channelId).add(e.id),this.markDirty();}get(e){return this.sessions.get(e)}async delete(e){let t=this.sessions.get(e);if(!t)return;this.sessions.delete(e);let s=this.channelSessions.get(t.channel.channelId);s&&(s.delete(e),s.size===0&&this.channelSessions.delete(t.channel.channelId)),this.markDirty();}getAll(){return [...this.sessions.values()]}getByChannel(e){let t=this.channelSessions.get(e);return t?[...t].map(s=>this.sessions.get(s)).filter(s=>s!==void 0):[]}size(){return this.sessions.size}markDirty(){this.isDirty=true;}async save(){if(!this.config.enablePersistence)return;let e=this.getSessionFilePath(),t=this.serializeAll();try{await this.ensureStorageDir(),await m.promises.writeFile(e,JSON.stringify(t,null,2),"utf-8"),this.isDirty=!1,this.log.debug("sessions saved",{count:t.length});}catch(s){throw this.log.error("failed to save sessions",{error:s}),s}}async load(){if(!this.config.enablePersistence)return;let e=this.getSessionFilePath();try{if(!m.existsSync(e)){this.log.debug("no saved sessions found");return}let t=await m.promises.readFile(e,"utf-8"),s=JSON.parse(t);this.sessions.clear(),this.channelSessions.clear();let n=Date.now(),r=this.config.maxRetentionDays*24*60*60*1e3;for(let a of s){if(n-a.lastActiveAt>r)continue;let g={id:a.id,channel:a.channel,backendSessionId:a.backendSessionId,subscribers:new Set(a.subscribers),state:a.state,createdAt:a.createdAt,lastActiveAt:a.lastActiveAt};this.sessions.set(g.id,g),this.channelSessions.has(g.channel.channelId)||this.channelSessions.set(g.channel.channelId,new Set),this.channelSessions.get(g.channel.channelId).add(g.id);}this.log.info("sessions loaded",{loaded:this.sessions.size,skipped:s.length-this.sessions.size});}catch(t){this.log.error("failed to load sessions",{error:t});}}serializeAll(){let e=[];for(let t of this.sessions.values())e.push(this.serialize(t));return e}serialize(e){return {id:e.id,channel:e.channel,backendSessionId:e.backendSessionId,subscribers:[...e.subscribers],state:e.state,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt}}getSessionFilePath(){return z.join(this.config.storagePath,"sessions.json")}async ensureStorageDir(){m.existsSync(this.config.storagePath)||await m.promises.mkdir(this.config.storagePath,{recursive:true});}startAutoSave(){this.autoSaveTimer||(this.autoSaveTimer=setInterval(async()=>{this.isDirty&&await this.save();},this.config.autoSaveInterval));}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null);}async cleanup(){let e=Date.now(),t=this.config.maxRetentionDays*24*60*60*1e3,s=[];for(let n of this.sessions.values())e-n.lastActiveAt>t&&s.push(n.id);for(let n of s)await this.delete(n);return s.length>0&&(this.log.info("cleaned up expired sessions",{count:s.length}),await this.save()),s.length}getStats(){let e={total:this.sessions.size,byStatus:{active:0,idle:0,closed:0},byPlatform:{}};for(let t of this.sessions.values()){e.byStatus[t.state.status]++;let s=t.channel.platform;e.byPlatform[s]=(e.byPlatform[s]||0)+1;}return e}};var w=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:session"}));e(this,"sessionStore");e(this,"config");e(this,"initialized",false);this.config={enablePersistence:e$1.enablePersistence??true,storagePath:e$1.storagePath??"./data/gateway-sessions",autoSaveInterval:e$1.autoSaveInterval??6e4,maxRetentionDays:e$1.maxRetentionDays??7},this.sessionStore=new M({storagePath:this.config.storagePath,autoSaveInterval:this.config.autoSaveInterval,maxRetentionDays:this.config.maxRetentionDays,enablePersistence:this.config.enablePersistence});}async initialize(){this.initialized||(await this.sessionStore.initialize(),this.initialized=true,this.log.info("session manager initialized",{sessionCount:this.sessionStore.size(),persistenceEnabled:this.config.enablePersistence}));}async close(){await this.sessionStore.close(),this.log.info("session manager closed");}async getOrCreate(e,t={}){let s=E(e),n=this.sessionStore.get(s);return n?(n.lastActiveAt=Date.now(),this.log.debug("session found",{sessionId:s}),n):(n={id:s,channel:e,backendSessionId:null,subscribers:new Set,state:D(),createdAt:Date.now(),lastActiveAt:Date.now()},await this.sessionStore.set(n),this.log.info("session created",{sessionId:s,platform:e.platform,channelId:e.channelId,chatId:e.chatId,userId:e.userId}),n)}get(e){return this.sessionStore.get(e)}async closeSession(e){let t=this.sessionStore.get(e);if(!t){this.log.warn("session not found",{sessionId:e});return}t.state.status="closed",await this.sessionStore.delete(e),this.log.info("session closed",{sessionId:e});}async closeById(e){return this.closeSession(e)}async bindBackendSession(e,t){let s=this.sessionStore.get(e);if(!s)throw new Error(`Session not found: ${e}`);s.backendSessionId=t,await this.sessionStore.set(s),this.log.info("backend session bound",{gatewaySessionId:e,backendSessionId:t});}async unbindBackendSession(e){let t=this.sessionStore.get(e);if(!t){this.log.warn("session not found",{sessionId:e});return}t.backendSessionId=null,await this.sessionStore.set(t),this.log.info("backend session unbound",{gatewaySessionId:e});}getState(e){return this.sessionStore.get(e)?.state}async incrementMessageCountOrCreate(e,t){let s=this.sessionStore.get(e);if(!s){let n=t??{platform:"api",channelId:"default"};s=await this.getOrCreate(n);}return s.state.messageCount++,s.state.lastMessageAt=Date.now(),s.lastActiveAt=Date.now(),await this.sessionStore.set(s),s}async incrementMessageCount(e){let t=this.sessionStore.get(e);t&&(t.state.messageCount++,t.state.lastMessageAt=Date.now(),t.lastActiveAt=Date.now(),await this.sessionStore.set(t));}async addSubscriber(e,t){let s=this.sessionStore.get(e);if(!s){this.log.warn("session not found",{sessionId:e});return}s.subscribers.add(t),await this.sessionStore.set(s),this.log.debug("subscriber added to session",{sessionId:e,subscriberId:t});}async removeSubscriber(e,t){let s=this.sessionStore.get(e);s&&(s.subscribers.delete(t),await this.sessionStore.set(s),this.log.debug("subscriber removed from session",{sessionId:e,subscriberId:t}));}query(e){let t=this.sessionStore.getAll();return e.platform&&(t=t.filter(s=>s.channel.platform===e.platform)),e.channelId&&(t=t.filter(s=>s.channel.channelId===e.channelId)),e.userId&&(t=t.filter(s=>s.channel.userId===e.userId)),e.status&&(t=t.filter(s=>s.state.status===e.status)),t}getSessionsByChannel(e){return this.sessionStore.getByChannel(e)}getAllSessions(){return this.sessionStore.getAll()}getSessionCount(){return this.sessionStore.size()}async cleanupIdleSessions(e){let t=Date.now(),s=[];for(let n of this.sessionStore.getAll())n.state.status==="idle"&&t-n.lastActiveAt>e&&s.push(n.id);for(let n of s)await this.closeSession(n);return s.length>0&&this.log.info("cleaned up idle sessions",{count:s.length}),s.length}async save(){this.log.debug("session save triggered");}getStats(){return this.sessionStore.getStats()}};a();var I=class{constructor(e$1={}){e(this,"log",a$1.create({service:"gateway:plugin-loader"}));e(this,"plugins",new Map);e(this,"messageHandler",null);e(this,"healthCheckTimer",null);e(this,"config");this.config={pluginDir:e$1.pluginDir??"./plugins",autoDiscover:e$1.autoDiscover??false,healthCheckInterval:e$1.healthCheckInterval??6e4,healthCheckTimeout:e$1.healthCheckTimeout??5e3};}setMessageHandler(e){this.messageHandler=e;}async register(e,t){if(this.plugins.has(e.id)){this.log.warn("plugin already registered",{id:e.id});return}this.plugins.set(e.id,{plugin:e,config:t,started:false}),this.log.info("plugin registered",{id:e.id,platform:e.platform,name:e.name});}async unregister(e){let t=this.plugins.get(e);if(!t){this.log.warn("plugin not found",{id:e});return}t.started&&await this.stop(e),this.plugins.delete(e),this.log.info("plugin unregistered",{id:e});}async start(e){let t=this.plugins.get(e);if(!t)throw new Error(`Plugin not found: ${e}`);if(t.started){this.log.warn("plugin already started",{id:e});return}if(!this.messageHandler)throw new Error("Message handler not set");if(!t.config.enabled){this.log.warn("plugin is disabled",{id:e});return}this.log.info("starting plugin",{id:e});try{await t.plugin.start(t.config,this.messageHandler),t.started=!0,this.log.info("plugin started",{id:e});}catch(s){throw this.log.error("failed to start plugin",{id:e,error:String(s)}),s}}async stop(e){let t=this.plugins.get(e);if(!t){this.log.warn("plugin not found",{id:e});return}if(!t.started){this.log.warn("plugin not started",{id:e});return}this.log.info("stopping plugin",{id:e});try{await t.plugin.stop(),t.started=!1,this.log.info("plugin stopped",{id:e});}catch(s){throw this.log.error("failed to stop plugin",{id:e,error:String(s)}),s}}async startAll(){let e=[];for(let[t,s]of this.plugins){if(!s.config.enabled){this.log.debug("skipping disabled plugin",{id:t});continue}try{await this.start(t);}catch(n){e.push({id:t,error:n instanceof Error?n:new Error(String(n))});}}e.length>0&&this.log.warn("some plugins failed to start",{count:e.length,errors:e.map(t=>({id:t.id,error:t.error.message}))});}async stopAll(){let e=[];for(let[t,s]of this.plugins)if(s.started)try{await this.stop(t);}catch(n){e.push({id:t,error:n instanceof Error?n:new Error(String(n))});}e.length>0&&this.log.warn("some plugins failed to stop",{count:e.length,errors:e.map(t=>({id:t.id,error:t.error.message}))});}getPlugin(e){return this.plugins.get(e)?.plugin}getAllPlugins(){return [...this.plugins.values()].map(e=>e.plugin)}getRunningPlugins(){return [...this.plugins.values()].filter(e=>e.started).map(e=>e.plugin)}isRunning(e){return this.plugins.get(e)?.started??false}async healthCheck(e){let t=this.plugins.get(e);if(!t)return {healthy:false,lastCheck:Date.now(),error:"Plugin not found"};try{let s=await Promise.race([t.plugin.healthCheck(),new Promise((n,r)=>setTimeout(()=>r(new Error("Health check timeout")),this.config.healthCheckTimeout))]);return t.lastHealthCheck=s,s}catch(s){let n={healthy:false,lastCheck:Date.now(),error:s instanceof Error?s.message:String(s)};return t.lastHealthCheck=n,n}}async healthCheckAll(){let e=new Map;for(let[t]of this.plugins)e.set(t,await this.healthCheck(t));return e}startHealthCheckTimer(){if(this.healthCheckTimer){this.log.warn("health check timer already running");return}this.healthCheckTimer=setInterval(async()=>{let e=await this.healthCheckAll();for(let[t,s]of e)s.healthy||this.log.warn("plugin health check failed",{id:t,error:s.error});},this.config.healthCheckInterval),this.log.info("health check timer started",{interval:this.config.healthCheckInterval});}stopHealthCheckTimer(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null,this.log.info("health check timer stopped"));}async sendToPlugin(e,t){let s=this.plugins.get(e);if(!s)throw new Error(`Plugin not found: ${e}`);if(!s.started)throw new Error(`Plugin not started: ${e}`);return s.plugin.send(t)}};a();var l=a$1.create({service:"gateway:websocket-server"});function J(){return `ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function R(c,e){for(let[t,s]of e.entries())if(s===c)return t;return null}var G=class{constructor(e$1={}){e(this,"config");e(this,"server",null);e(this,"wss",null);e(this,"httpsServer",null);e(this,"httpRedirectServer",null);e(this,"connections",new Map);e(this,"subscriptions",new Map);e(this,"sessionSubscriptions",new Map);e(this,"sessionLastActivity",new Map);e(this,"cleanupInterval",null);e(this,"heartbeatInterval",null);e(this,"startTime",0);e(this,"running",false);this.config={..._,...e$1};}async start(){if(this.running){l.warn("WebSocket server is already running");return}l.info("Starting WebSocket server",{port:this.config.port,hostname:this.config.hostname,path:this.config.path,https:this.config.https?.enabled??false}),this.startTime=Date.now();let e={onOpen:(s,n)=>{this.handleConnection(n);},onMessage:async(s,n)=>{try{let r=JSON.parse(s.data.toString());await this.handleMessage(n,r);}catch(r){l.error("Error processing WebSocket message",{error:r.message}),this.sendError(n,r.message);}},onClose:(s,n)=>{this.handleDisconnection(n);},onError:(s,n)=>{l.error("WebSocket error",{error:s.type});}};this.config.https?.enabled?await this.startHTTPSServer(e):await this.startHTTPServer(e),this.cleanupInterval=setInterval(()=>this.cleanupExpiredSessions(),3e4),this.heartbeatInterval=setInterval(()=>this.checkConnectionTimeout(),this.config.heartbeatInterval),this.running=true;let t=this.config.https?.enabled?"wss":"ws";l.info("WebSocket server started",{url:`${t}://${this.config.hostname}:${this.config.port}${this.config.path}`});}async startHTTPServer(e){this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true});let t=this.server.raw;t&&this.setupWebSocketUpgrade(t,e);}async startHTTPSServer(e){let t=this.config.https,s=this.loadSSLCertificates(t);if(!s){l.error("Failed to load SSL certificates, falling back to HTTP"),await this.startHTTPServer(e);return}this.server=createServer({port:this.config.port,hostname:this.config.hostname,routes:this.createRoutes(),timeout:this.config.connectionTimeout,cors:true});let n=this.server.raw;this.httpsServer=V.createServer(s,n.listeners("request")[0]),this.setupWebSocketUpgrade(this.httpsServer,e),await new Promise(r=>{this.httpsServer.listen(this.config.port,this.config.hostname,()=>{l.info("HTTPS server started",{port:this.config.port,hostname:this.config.hostname}),r();});}),t.forceRedirect&&t.httpPort&&this.startHTTPRedirectServer(t.httpPort);}loadSSLCertificates(e){try{return e.cert&&e.key?{cert:e.cert,key:e.key}:e.certPath&&e.keyPath?{cert:m__default.readFileSync(e.certPath),key:m__default.readFileSync(e.keyPath)}:null}catch(t){return l.error("Failed to load SSL certificates",{error:t.message}),null}}setupWebSocketUpgrade(e,t){this.wss=new WebSocketServer({noServer:true}),e.on("upgrade",(s,n,r)=>{try{let g=new URL(s.url||"/",`http://${s.headers.host}`).pathname;(g===this.config.path||this.config.path==="/"&&(g==="/"||g===""))&&this.wss.handleUpgrade(s,n,r,u=>{t.onOpen?.({type:"open"},u),u.on("message",f=>{t.onMessage?.({data:f},u);}),u.on("close",(f,L)=>{t.onClose?.({code:f,reason:L},u);}),u.on("error",f=>{t.onError?.({type:"error",message:f.message},u);});});}catch{}});}startHTTPRedirectServer(e){this.httpRedirectServer=K.createServer((t,s)=>{let r=`https://${t.headers.host?.split(":")[0]||this.config.hostname}:${this.config.port}${t.url}`;l.debug("Redirecting HTTP to HTTPS",{from:t.url,to:r}),s.writeHead(301,{Location:r,"Content-Type":"text/plain"}),s.end(`Redirecting to ${r}`);}),this.httpRedirectServer.listen(e,this.config.hostname,()=>{l.info("HTTP redirect server started",{port:e,hostname:this.config.hostname});});}async stop(){if(!this.running){l.warn("WebSocket server is not running");return}l.info("Stopping WebSocket server"),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let[e,t]of this.connections.entries())try{t.close(1e3,"Server shutting down");}catch(s){l.debug("Error closing connection",{clientId:e,error:String(s)});}this.connections.clear(),this.subscriptions.clear(),this.sessionSubscriptions.clear(),this.sessionLastActivity.clear(),this.wss&&(this.wss.close(),this.wss=null),this.httpsServer&&(await new Promise(e=>{this.httpsServer.close(()=>e());}),this.httpsServer=null),this.httpRedirectServer&&(await new Promise(e=>{this.httpRedirectServer.close(()=>e());}),this.httpRedirectServer=null),this.server&&(await this.server.stop(),this.server=null),this.running=false,l.info("WebSocket server stopped");}broadcastToSession(e,t){this.touchSession(e);let s=this.sessionSubscriptions.get(e);if(!s||s.size===0){l.debug("No clients subscribed to session",{sessionId:e});return}let n=t?.properties?.sessionID;if(typeof n=="string"&&n&&n!==e)return;let r=JSON.stringify({type:"event",sessionId:e,payload:t});for(let a of s){let g=this.subscriptions.get(a);if(g&&g.ws.readyState===g.ws.OPEN&&g.subscribedSessions.has(e)){if(g.subscribedEventTypes.size>0&&!g.subscribedEventTypes.has(t.type)){l.debug("Event type not subscribed, skipping",{clientId:a,sessionId:e,eventType:t.type,subscribedTypes:Array.from(g.subscribedEventTypes)});continue}g.ws.send(r),l.debug("Event pushed to client",{clientId:a,sessionId:e,eventType:t.type});}}}getConnectionCount(){return this.connections.size}getSubscriptionCount(){return this.sessionSubscriptions.size}getConnectionInfos(){let e=[];for(let[t,s]of this.subscriptions.entries())e.push({clientId:t,state:s.ws.readyState===s.ws.OPEN?"connected":"disconnected",connectedAt:s.connectedAt,lastActivityAt:s.lastActivityAt,authInfo:s.authInfo});return e}isRunning(){return this.running}handleConnection(e){if(this.connections.size>=(this.config.maxConnections??v.maxConnections)){l.warn("Maximum connections reached, rejecting new connection"),e.close(1013,"Maximum connections reached");return}let t=J();this.connections.set(t,e),this.subscriptions.set(t,{clientId:t,ws:e,subscribedSessions:new Set,subscribedEventTypes:new Set,connectedAt:Date.now(),lastActivityAt:Date.now()}),l.info("WebSocket client connected",{clientId:t,totalConnections:this.connections.size}),this.sendMessage(e,{type:"connected",clientId:t,payload:{version:"1.0.0",capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}handleDisconnection(e){let t=R(e,this.connections);if(!t)return;this.connections.delete(t);let s=this.subscriptions.get(t);if(s){for(let n of s.subscribedSessions){let r=this.sessionSubscriptions.get(n);r&&(r.delete(t),r.size===0&&this.sessionSubscriptions.delete(n));}this.subscriptions.delete(t);}l.info("WebSocket client disconnected",{clientId:t,totalConnections:this.connections.size});}async handleMessage(e,t){let s=R(e,this.connections);if(!s){this.sendError(e,"Client not found");return}let n=this.subscriptions.get(s);switch(n&&(n.lastActivityAt=Date.now()),t.type){case "ping":this.sendMessage(e,{type:"pong"});break;case "initialize":await this.handleInitialize(e,t);break;case "subscribe":await this.handleSubscribe(e,t);break;case "unsubscribe":await this.handleUnsubscribe(e,t);break;case "message":await this.handleMessageRequest(e,t);break;case "interrupt":await this.handleInterrupt(e,t);break;case "releaseSubscription":await this.handleReleaseSubscription(e,t);break;default:this.sendError(e,`Unknown message type: ${t.type}`);}}async handleInitialize(e,t){this.sendMessage(e,{type:"initialize_response",success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"]}});}async handleSubscribe(e,t){if(t.type!=="subscribe"||!t.sessionId){this.sendError(e,"Invalid subscribe request");return}let s=R(e,this.connections);if(!s){this.sendError(e,"Client not found");return}let n=this.subscriptions.get(s);if(!n){this.sendError(e,"Subscription not found");return}if(n.subscribedSessions.add(t.sessionId),this.sessionSubscriptions.has(t.sessionId)||this.sessionSubscriptions.set(t.sessionId,new Set),this.sessionSubscriptions.get(t.sessionId).add(s),this.touchSession(t.sessionId),t.payload?.eventTypes)for(let r of t.payload.eventTypes)n.subscribedEventTypes.add(r);l.info("Client subscribed to session",{clientId:s,sessionId:t.sessionId}),this.sendMessage(e,{type:"subscribed",sessionId:t.sessionId});}async handleUnsubscribe(e,t){if(t.type!=="unsubscribe"||!t.sessionId){this.sendError(e,"Invalid unsubscribe request");return}let s=R(e,this.connections);if(!s)return;let n=this.subscriptions.get(s);if(!n)return;n.subscribedSessions.delete(t.sessionId);let r=this.sessionSubscriptions.get(t.sessionId);r&&(r.delete(s),r.size===0&&this.sessionSubscriptions.delete(t.sessionId)),l.info("Client unsubscribed from session",{clientId:s,sessionId:t.sessionId}),this.sendMessage(e,{type:"unsubscribed",sessionId:t.sessionId});}async handleMessageRequest(e,t){if(t.type!=="message"||!t.sessionId||!t.payload){this.sendError(e,"Invalid message request");return}l.debug("Message received",{sessionId:t.sessionId}),this.sendMessage(e,{type:"response",sessionId:t.sessionId,success:true,result:{received:true}});}async handleInterrupt(e,t){if(t.type!=="interrupt"||!t.sessionId){this.sendError(e,"Invalid interrupt request");return}l.info("Interrupt requested via WebSocket",{sessionId:t.sessionId}),this.sendMessage(e,{type:"interrupted",sessionId:t.sessionId,success:true});}async handleReleaseSubscription(e,t){if(t.type!=="releaseSubscription"||!t.sessionId){this.sendError(e,"Invalid releaseSubscription request");return}l.info("Release subscription requested via WebSocket",{sessionId:t.sessionId}),this.releaseSessionResources(t.sessionId),this.sendMessage(e,{type:"subscriptionReleased",sessionId:t.sessionId});}touchSession(e){this.sessionLastActivity.set(e,Date.now());}checkConnectionTimeout(){let e=Date.now(),t=this.config.connectionTimeout??v.connectionTimeout,s=[];for(let[n,r]of this.subscriptions.entries())e-r.lastActivityAt>t&&s.push(n);for(let n of s){let r=this.subscriptions.get(n);if(r){l.info("Closing inactive connection",{clientId:n,lastActivityAt:r.lastActivityAt,timeoutMs:t});try{r.ws.close(1001,"Connection timeout");}catch(a){l.debug("Error closing timed out connection",{clientId:n,error:String(a)});}}}s.length>0&&l.debug("Closed timed out connections",{count:s.length,remainingConnections:this.connections.size-s.length});}cleanupExpiredSessions(){let e=Date.now(),t=[],s=this.config.sessionExpireMs??v.sessionExpireMs;for(let[n,r]of this.sessionLastActivity.entries())e-r>s&&t.push(n);for(let n of t)l.info("Session expired due to inactivity, releasing resources",{sessionId:n,lastActivity:this.sessionLastActivity.get(n),expireMs:s}),this.releaseSessionResources(n),this.sessionLastActivity.delete(n);t.length>0&&l.debug("Cleaned up expired sessions",{count:t.length,remainingActive:this.sessionLastActivity.size});}releaseSessionResources(e){let t=this.sessionSubscriptions.get(e);if(t){for(let s of t){let n=this.subscriptions.get(s);n&&n.ws.readyState===n.ws.OPEN&&this.sendMessage(n.ws,{type:"session_closed",sessionId:e,payload:{reason:"Session resources released due to expiration or explicit release"}});}for(let s of t){let n=this.subscriptions.get(s);n&&n.subscribedSessions.delete(e);}this.sessionSubscriptions.delete(e),l.info("Session resources released",{sessionId:e,clientCount:t.size});}}sendMessage(e,t){e.readyState===e.OPEN&&e.send(JSON.stringify(t));}sendError(e,t,s){this.sendMessage(e,{type:"error",message:t,code:s});}createRoutes(){return [{method:"get",path:"/health",handler:e=>{let t={status:"healthy",timestamp:Date.now(),version:"1.0.0"};return e.json(t)}},{method:"get",path:"/status",handler:e=>{let t={status:this.running?"running":"stopped",connections:this.connections.size,sessions:this.sessionSubscriptions.size,subscriptions:this.subscriptions.size,uptime:this.running?Date.now()-this.startTime:0,version:"1.0.0"};return e.json(t)}},{method:"post",path:"/initialize",handler:async e=>{let t=await e.req.json().catch(()=>({}));return l.debug("ACP initialize request received",{body:t}),e.json({success:true,result:{capabilities:["subscribe","message","interrupt","releaseSubscription"],version:"1.0.0"}})}},{method:"post",path:"/session",handler:async e=>{await e.req.json().catch(()=>({}));let n={id:`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,createdAt:Date.now()};return e.json(n)}},{method:"post",path:"/session/:sessionId/prompt",handler:async e=>{let t=e.req.param("sessionId");await e.req.json().catch(()=>({}));if(!t)return e.json({error:"No sessionId provided"},400);let r={messageId:`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,sessionId:t,createdAt:Date.now()};return e.status(202),e.json(r)}},{method:"get",path:"/subscriptions",handler:e=>{let t=Array.from(this.sessionSubscriptions.entries()).map(([n,r])=>({sessionId:n,subscriberCount:r.size,subscribers:Array.from(r)})),s={subscriptions:t,total:t.length};return e.json(s)}}]}};function Y(c){let e={platform:c.channel?.platform??"api",channelId:c.channel?.channelId??"unknown",chatId:c.channel?.chatId,userId:c.channel?.userId};return {id:c.messageId??`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:c.sessionId,type:c.type,content:Array.isArray(c.content)?c.content:[{type:"text",text:String(c.content??"")}],metadata:{channel:e,replyToMessageId:c.replyToMessageId},timestamp:c.timestamp??Date.now()}}var B=class{constructor(e$1){e(this,"log",a$1.create({service:"gateway:server"}));e(this,"config");e(this,"router");e(this,"sessionManager");e(this,"pluginLoader");e(this,"messageStore");e(this,"running",false);e(this,"connections",0);this.config=e$1,this.router=new P,this.sessionManager=new w,this.pluginLoader=new I({healthCheckInterval:6e4});let t=R$1(),s=O();this.messageStore=new C({storagePath:`${t.Path.data}/gateway-messages`}),s&&P$1().setMessageStorage({store:async r=>{let a=Y(r);await this.messageStore.store(a);},updateStatus:async(r,a,g)=>{await this.messageStore.updateStatus(r,a,g);}}),this.pluginLoader.setMessageHandler({onMessage:n=>this.onMessage(n),onEvent:n=>this.onEvent(n)});}async start(){if(this.running){this.log.warn("gateway server is already running");return}this.log.info("starting gateway server",{port:this.config.port,hostname:this.config.hostname}),await this.sessionManager.initialize(),await this.pluginLoader.startAll(),this.pluginLoader.startHealthCheckTimer(),this.running=true,this.log.info("gateway server started");}async stop(){if(!this.running){this.log.warn("gateway server is not running");return}this.log.info("stopping gateway server"),this.pluginLoader.stopHealthCheckTimer(),await this.pluginLoader.stopAll(),await this.router.shutdown(),await this.sessionManager.close(),this.running=false,this.log.info("gateway server stopped");}getStatus(){return {running:this.running,port:this.config.port,hostname:this.config.hostname,connections:this.connections}}async onMessage(e){if(this.log.debug("message received",{id:e.id,sessionId:e.sessionId,type:e.type}),this.messageStore.isProcessed(e.id)){this.log.warn("message already processed, skipping",{id:e.id});return}await this.storeMessage(e),await this.sessionManager.incrementMessageCountOrCreate(e.sessionId,e.metadata.channel),(await this.router.route(e)).broadcastCount===0&&e.type==="input"&&this.log.debug("no subscribers, message pending",{id:e.id});}async storeMessage(e){if(await this.messageStore.store(e),O())try{let t=P$1(),s={name:HookEvent.GatewayMessageReceive,data:{messageId:e.id,sessionId:e.sessionId,type:e.type,content:e.content,channel:e.metadata.channel,replyToMessageId:e.metadata.replyToMessageId,timestamp:e.timestamp||Date.now()}};await t.hookRegistry.emit(s);}catch{this.log.debug("hook trigger skipped (no context)");}}async processMessage(e,t,s,n={}){if(await this.messageStore.updateStatus(t,"processing",{processedBy:s}),O())try{await P$1().hookRegistry.emit({name:HookEvent.GatewayMessageProcess,data:{messageId:t,sessionId:e,processorId:s,processType:n.processType||"direct",agent:n.agent,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}}async completeMessage(e,t,s,n={}){let{success:r=true,error:a,responseMessageId:g,tokens:u,duration:f}=n;if(await this.messageStore.updateStatus(t,r?"completed":"failed",{processedBy:s,error:a}),O())try{await P$1().hookRegistry.emit({name:HookEvent.GatewayMessageComplete,data:{messageId:t,sessionId:e,processorId:s,status:r?"completed":"failed",error:a,responseMessageId:g,tokens:u,duration:f,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}await this.router.completeMessage(e,t,s,r?"completed":"failed");}async onEvent(e){switch(this.log.debug("channel event",{type:e.type,channelId:e.channelId}),e.type){case "connected":this.connections++;break;case "disconnected":this.connections--;break;case "error":this.log.error("channel error",{channelId:e.channelId,data:e.data});break}}async registerChannel(e,t){let s=t??{enabled:true,platform:{},session:{autoCreate:true,resetPolicy:"onNewConversation"},routing:{broadcast:true,dispatchToSubAgent:false}};await this.pluginLoader.register(e,s),this.running&&await this.pluginLoader.start(e.id);}async unregisterChannel(e){await this.pluginLoader.unregister(e);}async subscribe(e,t){await this.router.subscribe(e,t),await this.sessionManager.addSubscriber(e,t.id);}async unsubscribe(e){await this.router.unsubscribe(e);}async send(e){await this.onMessage(e);}async sendToChannel(e,t,s={}){let{proactive:n=false,replyToMessageId:r}=s;if(O())try{await P$1().hookRegistry.emit({name:HookEvent.GatewayMessageSend,data:{messageId:t.id,sessionId:t.sessionId,type:t.type,channel:t.metadata.channel,proactive:n,replyToMessageId:r,timestamp:Date.now()}});}catch{this.log.debug("hook trigger skipped (no context)");}return this.pluginLoader.sendToPlugin(e,t)}async sendProactiveMessage(e,t,s,n){let r={id:`msg_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:t,type:"output",content:s,metadata:{channel:n},timestamp:Date.now()};return this.sendToChannel(e,r,{proactive:true})}getSessionManager(){return this.sessionManager}getRouter(){return this.router}getPluginLoader(){return this.pluginLoader}getMessageStore(){return this.messageStore}async getMessageHistory(e,t){return this.messageStore.getSessionHistory(e,t)}};
|
|
2
2
|
export{x as a,k as b,W as c,q as d,E as e,D as f,A as g,_ as h,F as i,U as j,$ as k,j as l,P as m,C as n,M as o,w as p,I as q,G as r,B as s};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkBOHNPDOJ_cjs=require('./chunk-BOHNPDOJ.cjs'),chunkSIOB4FC7_cjs=require('./chunk-SIOB4FC7.cjs');require('./chunk-XQVVSJRM.cjs');var promises=require('fs/promises'),o=require('path'),xdgBasedir=require('xdg-basedir'),x=require('os');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var o__default=/*#__PURE__*/_interopDefault(o);var x__default=/*#__PURE__*/_interopDefault(x);chunkSIOB4FC7_cjs.a();var s="easbot",c=o__default.default.join(xdgBasedir.xdgData,s),H=o__default.default.join(xdgBasedir.xdgCache,s),N=o__default.default.join(xdgBasedir.xdgConfig,s),j=o__default.default.join(xdgBasedir.xdgState,s);exports.Global=void 0;(e=>{e.Path={get home(){return process.env.EASBOT_TEST_HOME||x__default.default.homedir()},data:c,bin:o__default.default.join(c,"bin"),log:o__default.default.join(c,"log"),cache:H,config:N,state:j};let t=null,n=null;async function A(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{let r=await import('./package-2UGUDLKV.cjs');t=r.default?.version||r.version||"local";}catch{t="local";}return t||"local"}function E(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{t=chunkBOHNPDOJ_cjs.a.version||"local";}catch{t="local";}return t||"local"}e.getVersion=E;function l(){if(n)return n;if(process.env.EASBOT_CHANNEL)return n=process.env.EASBOT_CHANNEL,n;let r=E();return r==="local"||r.includes("dev")?n="local":r.includes("beta")||r.includes("alpha")?n="preview":n="latest",n||"local"}e.getChannel=l;function C(){return l()==="local"}e.isLocal=C;function V(){return l()==="preview"}e.isPreview=V;let u=false,a=null;async function I(){if(!u)return a||(a=(async()=>{await A(),await Promise.all([promises.mkdir(e.Path.data,{recursive:true}),promises.mkdir(e.Path.config,{recursive:true}),promises.mkdir(e.Path.state,{recursive:true}),promises.mkdir(e.Path.log,{recursive:true}),promises.mkdir(e.Path.bin,{recursive:true}),promises.mkdir(e.Path.cache,{recursive:true})]).then(()=>{process.env.EASBOT_DATA_PATH=e.Path.data,process.env.EASBOT_CONFIG_PATH=e.Path.config,process.env.EASBOT_STATE_PATH=e.Path.state,process.env.EASBOT_LOG_PATH=e.Path.log,process.env.EASBOT_BIN_PATH=e.Path.bin,process.env.EASBOT_CACHE_PATH=e.Path.cache;});let r="1",h=o__default.default.join(e.Path.cache,"version");if(await promises.readFile(h,"utf-8").catch(()=>"0")!==r){try{let p=await promises.readdir(e.Path.cache);await Promise.all(p.map(g=>promises.rm(o__default.default.join(e.Path.cache,g),{recursive:!0,force:!0})));}catch{}await promises.writeFile(h,r);}u=true;})(),a)}e.init=I;})(exports.Global||(exports.Global={}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-VVZG6LF6.mjs';import {a}from'./chunk-SJNPXLNN.mjs';import'./chunk-TY6W6O7O.mjs';import {mkdir,readFile,readdir,rm,writeFile}from'fs/promises';import o from'path';import {xdgData,xdgCache,xdgConfig,xdgState}from'xdg-basedir';import x from'os';a();var s="easbot",c=o.join(xdgData,s),H=o.join(xdgCache,s),N=o.join(xdgConfig,s),j=o.join(xdgState,s),P;(e=>{e.Path={get home(){return process.env.EASBOT_TEST_HOME||x.homedir()},data:c,bin:o.join(c,"bin"),log:o.join(c,"log"),cache:H,config:N,state:j};let t=null,n=null;async function A(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{let r=await import('./package-UZJDAOIA.mjs');t=r.default?.version||r.version||"local";}catch{t="local";}return t||"local"}function E(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{t=a$1.version||"local";}catch{t="local";}return t||"local"}e.getVersion=E;function l(){if(n)return n;if(process.env.EASBOT_CHANNEL)return n=process.env.EASBOT_CHANNEL,n;let r=E();return r==="local"||r.includes("dev")?n="local":r.includes("beta")||r.includes("alpha")?n="preview":n="latest",n||"local"}e.getChannel=l;function C(){return l()==="local"}e.isLocal=C;function V(){return l()==="preview"}e.isPreview=V;let u=false,a=null;async function I(){if(!u)return a||(a=(async()=>{await A(),await Promise.all([mkdir(e.Path.data,{recursive:true}),mkdir(e.Path.config,{recursive:true}),mkdir(e.Path.state,{recursive:true}),mkdir(e.Path.log,{recursive:true}),mkdir(e.Path.bin,{recursive:true}),mkdir(e.Path.cache,{recursive:true})]).then(()=>{process.env.EASBOT_DATA_PATH=e.Path.data,process.env.EASBOT_CONFIG_PATH=e.Path.config,process.env.EASBOT_STATE_PATH=e.Path.state,process.env.EASBOT_LOG_PATH=e.Path.log,process.env.EASBOT_BIN_PATH=e.Path.bin,process.env.EASBOT_CACHE_PATH=e.Path.cache;});let r="1",h=o.join(e.Path.cache,"version");if(await readFile(h,"utf-8").catch(()=>"0")!==r){try{let p=await readdir(e.Path.cache);await Promise.all(p.map(g=>rm(o.join(e.Path.cache,g),{recursive:!0,force:!0})));}catch{}await writeFile(h,r);}u=true;})(),a)}e.init=I;})(P||(P={}));export{P as Global};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkBOHNPDOJ_cjs=require('./chunk-BOHNPDOJ.cjs');require('./chunk-XQVVSJRM.cjs');module.exports=chunkBOHNPDOJ_cjs.a;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as default}from'./chunk-VVZG6LF6.mjs';import'./chunk-TY6W6O7O.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkCTTZF7B6_cjs=require('./chunk-CTTZF7B6.cjs');require('./chunk-EKLLH53Y.cjs'),require('./chunk-SIOB4FC7.cjs'),require('./chunk-XQVVSJRM.cjs');Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.q}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.s}});Object.defineProperty(exports,"GatewayWebSocketServer",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.r}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{q as ChannelPluginLoader,s as GatewayServer,r as GatewayWebSocketServer}from'./chunk-YAKKDECJ.mjs';import'./chunk-ETYFY7SI.mjs';import'./chunk-SJNPXLNN.mjs';import'./chunk-TY6W6O7O.mjs';
|
package/dist/cli.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkEOLBEWUW_cjs=require('./chunks/chunk-EOLBEWUW.cjs'),chunkEKLLH53Y_cjs=require('./chunks/chunk-EKLLH53Y.cjs'),chunkSIOB4FC7_cjs=require('./chunks/chunk-SIOB4FC7.cjs'),chunkXQVVSJRM_cjs=require('./chunks/chunk-XQVVSJRM.cjs'),utils=require('@easbot/utils');var v=chunkXQVVSJRM_cjs.c(F=>{chunkSIOB4FC7_cjs.a();var T=class extends Error{constructor(t,e,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0;}},P=class extends T{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name;}};F.CommanderError=T;F.InvalidArgumentError=P;});var H=chunkXQVVSJRM_cjs.c(D=>{chunkSIOB4FC7_cjs.a();var{InvalidArgumentError:Vt}=v(),R=class{constructor(t,e){switch(this.description=e||"",this.variadic=false,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case "<":this.required=true,this._name=t.slice(1,-1);break;case "[":this.required=false,this._name=t.slice(1,-1);break;default:this.required=true,this._name=t;break}this._name.endsWith("...")&&(this.variadic=true,this._name=this._name.slice(0,-3));}name(){return this._name}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new Vt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}argRequired(){return this.required=true,this}argOptional(){return this.required=false,this}};function Lt(r){let t=r.name()+(r.variadic===true?"...":"");return r.required?"<"+t+">":"["+t+"]"}D.Argument=R;D.humanReadableArgName=Lt;});var q=chunkXQVVSJRM_cjs.c(M=>{chunkSIOB4FC7_cjs.a();var{humanReadableArgName:It}=H(),N=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=false,this.sortOptions=false,this.showGlobalOptions=false;}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80;}visibleCommands(t){let e=t.commands.filter(n=>!n._hidden),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort((n,s)=>n.name().localeCompare(s.name())),e}compareOptions(t,e){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter(n=>!n.hidden),i=t._getHelpOption();if(i&&!i.hidden){let n=i.short&&t._findOption(i.short),s=i.long&&t._findOption(i.long);!n&&!s?e.push(i):i.long&&!s?e.push(t.createOption(i.long,i.description)):i.short&&!n&&e.push(t.createOption(i.short,i.description));}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return [];let e=[];for(let i=t.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);e.push(...n);}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||"";}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(i=>It(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(n)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(n)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let n=t.parent;n;n=n.parent)i=n.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatItemList(t,e,i){return e.length===0?[]:[i.styleTitle(t),...e,""]}groupItems(t,e,i){let n=new Map;return t.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]);}),e.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]),n.get(o).push(s);}),n}formatHelp(t,e){let i=e.padWidth(t,e),n=e.helpWidth??80;function s(c,d){return e.formatItem(c,i,d,e)}let o=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],a=e.commandDescription(t);a.length>0&&(o=o.concat([e.boxWrap(e.styleCommandDescription(a),n),""]));let h=e.visibleArguments(t).map(c=>s(e.styleArgumentTerm(e.argumentTerm(c)),e.styleArgumentDescription(e.argumentDescription(c))));if(o=o.concat(this.formatItemList("Arguments:",h,e)),this.groupItems(t.options,e.visibleOptions(t),c=>c.helpGroupHeading??"Options:").forEach((c,d)=>{let E=c.map(b=>s(e.styleOptionTerm(e.optionTerm(b)),e.styleOptionDescription(e.optionDescription(b))));o=o.concat(this.formatItemList(d,E,e));}),e.showGlobalOptions){let c=e.visibleGlobalOptions(t).map(d=>s(e.styleOptionTerm(e.optionTerm(d)),e.styleOptionDescription(e.optionDescription(d))));o=o.concat(this.formatItemList("Global Options:",c,e));}return this.groupItems(t.commands,e.visibleCommands(t),c=>c.helpGroup()||"Commands:").forEach((c,d)=>{let E=c.map(b=>s(e.styleSubcommandTerm(e.subcommandTerm(b)),e.styleSubcommandDescription(e.subcommandDescription(b))));o=o.concat(this.formatItemList(d,E,e));}),o.join(`
|
|
2
2
|
`)}displayWidth(t){return ot(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e==="[command]"?this.styleSubcommandText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleCommandText(e)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleSubcommandText(e)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}preformatted(t){return /\n[^\S\r\n]/.test(t)}formatItem(t,e,i,n){let o=" ".repeat(2);if(!i)return o+t;let a=t.padEnd(e+t.length-n.displayWidth(t)),h=2,l=(this.helpWidth??80)-e-h-2,c;return l<this.minWidthToWrap||n.preformatted(i)?c=i:c=n.boxWrap(i,l).replace(/\n/g,`
|
|
3
3
|
`+" ".repeat(e+h)),o+a+" ".repeat(h)+c.replace(/\n/g,`
|
|
4
4
|
${o}`)}boxWrap(t,e){if(e<this.minWidthToWrap)return t;let i=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,s=[];return i.forEach(o=>{let a=o.match(n);if(a===null){s.push("");return}let h=[a.shift()],p=this.displayWidth(h[0]);a.forEach(l=>{let c=this.displayWidth(l);if(p+c<=e){h.push(l),p+=c;return}s.push(h.join(""));let d=l.trimStart();h=[d],p=this.displayWidth(d);}),s.push(h.join(""));}),s.join(`
|
|
@@ -23,8 +23,8 @@ Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._life
|
|
|
23
23
|
`),this.outputHelp({error:true}));let i=e||{},n=i.exitCode||1,s=i.code||"commander.error";this._exit(n,s,t);}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in m.env){let e=t.attributeName();(this.getOptionValue(e)===void 0||["default","config","env"].includes(this.getOptionValueSource(e)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,m.env[t.envVar]):this.emit(`optionEnv:${t.name()}`));}});}_parseOptionsImplied(){let t=new Bt(this.options),e=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&e(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!e(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"implied");});});}missingArgument(t){let e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"});}optionMissingArgument(t){let e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"});}missingMandatoryOptionValue(t){let e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"});}_conflictingOption(t,e){let i=o=>{let a=o.attributeName(),h=this.getOptionValue(a),p=this.options.find(c=>c.negate&&a===c.attributeName()),l=this.options.find(c=>!c.negate&&a===c.attributeName());return p&&(p.presetArg===void 0&&h===false||p.presetArg!==void 0&&h===p.presetArg)?p:l||o},n=o=>{let a=i(o),h=a.attributeName();return this.getOptionValueSource(h)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${n(t)} cannot be used with ${n(e)}`;this.error(s,{code:"commander.conflictingOption"});}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);n=n.concat(o),s=s.parent;}while(s&&!s._enablePositionalOptions);e=ht(t,n);}let i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"});}_excessArguments(t){if(this._allowExcessArguments)return;let e=this.registeredArguments.length,i=e===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${e} argument${i} but got ${t.length}.`;this.error(s,{code:"commander.excessArguments"});}unknownCommand(){let t=this.args[0],e="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(s=>{n.push(s.name()),s.alias()&&n.push(s.alias());}),e=ht(t,n);}let i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"});}version(t,e,i){if(t===void 0)return this._version;this._version=t,e=e||"-V, --version",i=i||"output the version number";let n=this.createOption(e,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${t}
|
|
24
24
|
`),this._exit(0,"commander.version",t);}),this}description(t,e){return t===void 0&&e===void 0?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(e=this.commands[this.commands.length-1]),t===e._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${n}'`)}return e._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(e=>this.alias(e)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(i=>Mt(i));return [].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}helpGroup(t){return t===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=t,this)}commandsGroup(t){return t===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=t,this)}optionsGroup(t){return t===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=t,this)}_initOptionGroup(t){this._defaultOptionGroup&&!t.helpGroupHeading&&t.helpGroup(this._defaultOptionGroup);}_initCommandGroup(t){this._defaultCommandGroup&&!t.helpGroup()&&t.helpGroup(this._defaultCommandGroup);}nameFromFilename(t){return this._name=w.basename(t,w.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let e=this.createHelp(),i=this._getOutputContext(t);e.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=e.formatHelp(this,e);return i.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(t){t=t||{};let e=!!t.error,i,n,s;return e?(i=a=>this._outputConfiguration.writeErr(a),n=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),n=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:e,write:a=>(n||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:n,helpWidth:s}}outputHelp(t){let e;typeof t=="function"&&(e=t,t=void 0);let i=this._getOutputContext(t),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation({error:i.error});if(e&&(s=e(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",n));}helpOption(t,e){return typeof t=="boolean"?(t?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(t??"-h, --help",e??"display help for command"),(t||e)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let e=Number(m.exitCode??0);e===0&&t&&typeof t!="function"&&t.error&&(e=1),this._exit(e,"commander.help","(outputHelp)");}addHelpText(t,e){let i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw new Error(`Unexpected value for position to addHelpText.
|
|
25
25
|
Expecting one of '${i.join("', '")}'`);let n=`${t}Help`;return this.on(n,s=>{let o;typeof e=="function"?o=e({error:s.error,command:s.command}):o=e,o&&s.write(`${o}
|
|
26
|
-
`);}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(n=>e.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"));}};function pt(r){return r.map(t=>{if(!t.startsWith("--inspect"))return t;let e,i="127.0.0.1",n="9229",s;return (s=t.match(/^(--inspect(-brk)?)$/))!==null?e=s[1]:(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(e=s[1],/^\d+$/.test(s[3])?n=s[3]:i=s[3]):(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(e=s[1],i=s[3],n=s[4]),e&&n!=="0"?`${e}=${i}:${parseInt(n)+1}`:t})}function Y(){if(m.env.NO_COLOR||m.env.FORCE_COLOR==="0"||m.env.FORCE_COLOR==="false")return false;if(m.env.FORCE_COLOR||m.env.CLICOLOR_FORCE!==void 0)return true}Z.Command=J;Z.useColor=Y;});var _t=chunkXQVVSJRM_cjs.c(C=>{chunkSIOB4FC7_cjs.a();var{Argument:mt}=H(),{Command:Q}=dt(),{CommanderError:Ut,InvalidArgumentError:ft}=v(),{Help:zt}=q(),{Option:gt}=z();C.program=new Q;C.createCommand=r=>new Q(r);C.createOption=(r,t)=>new gt(r,t);C.createArgument=(r,t)=>new mt(r,t);C.Command=Q;C.Option=gt;C.Argument=mt;C.Help=zt;C.CommanderError=Ut;C.InvalidArgumentError=ft;C.InvalidOptionArgumentError=ft;});chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var Ot=chunkXQVVSJRM_cjs.d(_t(),1),{program:Se,createCommand:ve,createArgument:$e,createOption:Te,CommanderError:He,InvalidArgumentError:ke,InvalidOptionArgumentError:Ge,Command:yt,Argument:Ve,Option:Le,Help:Ie}=Ot.default;chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var Ct={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var Xt=Ct.languages,Jt=Xt.filter(r=>r.supported).map(r=>r.value),A={defaultLocale:"zh-CN",locales:Jt},$={},G=(r,t)=>{let e=$[r]||{translation:{}};return $[r]={translation:{...e.translation,...t.translation}},$[r]},V=(r=A.defaultLocale)=>($[r]||G(r,{translation:{}}),{locale:r,resources:$[r]||{translation:{}}});chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var Yt={translation:{"cli.startup.title":"Gateway WebSocket \u670D\u52A1\u5DF2\u542F\u52A8","cli.startup.status":"\u72B6\u6001","cli.startup.port":"\u7AEF\u53E3","cli.startup.hostname":"\u4E3B\u673A\u5730\u5740","cli.startup.protocol":"\u534F\u8BAE","cli.startup.connections":"\u8FDE\u63A5\u6570","cli.startup.running":"\u8FD0\u884C\u4E2D","cli.startup.stopped":"\u5DF2\u505C\u6B62","cli.startup.mode":"\u6A21\u5F0F","cli.startup.mode_standalone":"\u72EC\u7ACB\u6A21\u5F0F","cli.startup.mode_integrated":"\u96C6\u6210\u6A21\u5F0F","cli.status.title":"Gateway WebSocket \u670D\u52A1\u72B6\u6001","cli.stop.title":"Gateway WebSocket \u670D\u52A1\u5DF2\u505C\u6B62","cli.already_running":"Gateway \u670D\u52A1\u5DF2\u5728\u8FD0\u884C\u4E2D","cli.already_stopped":"Gateway \u670D\u52A1\u5DF2\u505C\u6B62","cli.shutdown_signal":"\u6536\u5230 {{signal}}\uFF0C\u6B63\u5728\u4F18\u96C5\u5173\u95ED...","cli.shutdown_success":"Gateway \u670D\u52A1\u5DF2\u6210\u529F\u505C\u6B62","cli.unknown_command":"\u672A\u77E5\u547D\u4EE4: {{command}}","cli.error.start_failed":"\u542F\u52A8 Gateway \u5931\u8D25","cli.error.stop_failed":"\u505C\u6B62 Gateway \u5931\u8D25","cli.error.restart_failed":"\u91CD\u542F Gateway \u5931\u8D25","cli.error.status_failed":"\u83B7\u53D6 Gateway \u72B6\u6001\u5931\u8D25","cli.error.shutdown":"\u5173\u95ED\u65F6\u53D1\u751F\u9519\u8BEF","cli.error.execution_failed":"CLI \u6267\u884C\u5931\u8D25","cli.error.detail":"\u9519\u8BEF\u8BE6\u60C5:","cli.command.start.desc":"\u542F\u52A8 Gateway WebSocket \u670D\u52A1","cli.command.stop.desc":"\u505C\u6B62 Gateway \u670D\u52A1","cli.command.restart.desc":"\u91CD\u542F Gateway \u670D\u52A1","cli.command.status.desc":"\u67E5\u770B Gateway \u670D\u52A1\u72B6\u6001","cli.option.directory":"\u5DE5\u4F5C\u76EE\u5F55","cli.option.port":"\u670D\u52A1\u7AEF\u53E3","cli.option.hostname":"\u4E3B\u673A\u5730\u5740","cli.option.debug":"\u542F\u7528\u8C03\u8BD5\u6A21\u5F0F","cli.help.command":"\u663E\u793A\u5E2E\u52A9\u4FE1\u606F","cli.program.description":"Gateway WebSocket \u670D\u52A1\u7BA1\u7406 CLI","cli.examples.title":"\u793A\u4F8B","cli.example.start":"\u542F\u52A8\u670D\u52A1","cli.example.stop":"\u505C\u6B62\u670D\u52A1","cli.example.restart":"\u91CD\u542F\u670D\u52A1","cli.example.hostname":"\u6307\u5B9A\u76D1\u542C\u5730\u5740"}},wt=Yt;chunkSIOB4FC7_cjs.a();var Zt={translation:{"cli.startup.title":"Gateway WebSocket Server Started","cli.startup.status":"Status","cli.startup.port":"Port","cli.startup.hostname":"Hostname","cli.startup.protocol":"Protocol","cli.startup.connections":"Connections","cli.startup.running":"Running","cli.startup.stopped":"Stopped","cli.startup.mode":"Mode","cli.startup.mode_standalone":"Standalone","cli.startup.mode_integrated":"Integrated","cli.status.title":"Gateway WebSocket Server Status","cli.stop.title":"Gateway WebSocket Server Stopped","cli.already_running":"Gateway server is already running.","cli.already_stopped":"Gateway server is already stopped.","cli.shutdown_signal":"Received {{signal}}, shutting down gracefully...","cli.shutdown_success":"Gateway stopped successfully.","cli.unknown_command":"Unknown command: {{command}}","cli.error.start_failed":"Failed to start gateway","cli.error.stop_failed":"Failed to stop gateway","cli.error.restart_failed":"Failed to restart gateway","cli.error.status_failed":"Failed to get gateway status","cli.error.shutdown":"Error during shutdown","cli.error.execution_failed":"CLI failed to execute","cli.error.detail":"Error detail:","cli.command.start.desc":"Start Gateway WebSocket service","cli.command.stop.desc":"Stop Gateway service","cli.command.restart.desc":"Restart Gateway service","cli.command.status.desc":"Check Gateway service status","cli.option.directory":"Working directory","cli.option.port":"Service port","cli.option.hostname":"Host address","cli.option.debug":"Enable debug mode","cli.help.command":"Display help information","cli.program.description":"Gateway WebSocket service management CLI","cli.examples.title":"Examples","cli.example.start":"Start service","cli.example.stop":"Stop service","cli.example.restart":"Restart service","cli.example.hostname":"Specify listening address"}},bt=Zt;var Qt=()=>{V("zh-CN"),V("en-US"),G("zh-CN",wt),G("en-US",bt);};Qt();var tt=new Map;var et=new Map;var te=r=>{if(et.has(r))return et.get(r);let t=/{{\s*(\w+)\s*}}/g,e=[],i;for(;(i=t.exec(r))!==null;){let o=i[1];o&&!e.includes(o)&&e.push(o);}let n=new RegExp("{{\\s*("+e.join("|")+")\\s*}}","g"),s={keys:e,regex:n};return et.set(r,s),s},xt=(r,t)=>{if(!r||typeof r!="string")return "";if(!t||Object.keys(t).length===0)return r;let{regex:e,keys:i}=te(r);return i.length===0||!i.some(s=>s in t)?r:r.replace(e,(s,o)=>{let a=t[o];return a==null?"":String(a)})},ee=r=>r&&A.locales.includes(r)?r:A.defaultLocale,At=r=>{if(!tt.has(r)){let{resources:t}=V(r);tt.set(r,t);}return tt.get(r)},ie=(r,t={})=>{let e=ee(t.locale),n=At(e)?.translation[r];if(n&&typeof n=="string"){let s=xt(n,t.vars);return s!=null?String(s):String(r)}if(e!==A.defaultLocale){let o=At(A.defaultLocale)?.translation[r];if(o&&typeof o=="string"){let a=xt(o,t.vars);return a!=null?String(a):String(r)}}return String(t.fallback??r)},u=ie;chunkSIOB4FC7_cjs.a();var O=chunkJJLKV5TO_cjs.a.create({service:"cli-gateway"}),I=58,Et="\u2551",St="\u2554",vt="\u255A",$t="\u2560",it="\u2550";function se(r,t=I){let e=t-r.length;return e<=0?r:r+" ".repeat(e)}function _(r){console.log(`${Et} ${se(r)} ${Et}`);}function nt(){console.log(`${St}${it.repeat(I)}${St.replace("\u2554","\u2557")}`);}function Tt(){console.log(`${$t}${it.repeat(I)}${$t.replace("\u2560","\u2563")}`);}function st(){console.log(`${vt}${it.repeat(I)}${vt.replace("\u255A","\u255D")}`);}function Ht(r){console.log(""),nt(),_(u("cli.startup.title")),Tt(),_(`${u("cli.startup.status")}: ${u("cli.startup.running").padEnd(37-u("cli.startup.status").length)}`),_(`${u("cli.startup.port")}: ${String(r.port).padEnd(37-u("cli.startup.port").length)}`),_(`${u("cli.startup.hostname")}: ${r.hostname.padEnd(37-u("cli.startup.hostname").length)}`),_(`${u("cli.startup.protocol")}: ws${" ".repeat(32)}`),r.connections!==void 0&&_(`${u("cli.startup.connections")}:${String(r.connections).padEnd(37-u("cli.startup.connections").length)}`),_(`${u("cli.startup.mode")}: ${(r.mode==="standalone"?u("cli.startup.mode_standalone"):u("cli.startup.mode_integrated")).padEnd(37-u("cli.startup.mode").length)}`),st(),console.log("");}function re(){console.log(""),nt(),_(u("cli.stop.title")),st(),console.log("");}async function oe(){try{let r=chunk53LJ4W4U_cjs.a.getStatus(),e=(await chunk53LJ4W4U_cjs.a.get())?.getStatus();console.log(""),nt(),_(u("cli.status.title")),Tt(),_(`${u("cli.startup.status")}: ${r.toUpperCase().padEnd(37-u("cli.startup.status").length)}`),e&&(_(`${u("cli.startup.port")}: ${String(e.port).padEnd(37-u("cli.startup.port").length)}`),_(`${u("cli.startup.hostname")}: ${(e.hostname||"localhost").padEnd(37-u("cli.startup.hostname").length)}`),_(`${u("cli.startup.connections")}:${String(e.connections||0).padEnd(37-u("cli.startup.connections").length)}`)),st(),console.log("");}catch(r){O.error("Failed to get gateway status",{error:r instanceof Error?r.message:String(r)}),console.error(`${u("cli.error.status_failed")}: ${r instanceof Error?r.message:String(r)}`),process.exit(1);}}async function ae(r){let t=r.directory||process.cwd();O.info("Starting gateway service",{port:r.port,hostname:r.hostname,directory:t});try{if(await chunk53LJ4W4U_cjs.a.init({directory:t,printLogs:r.debug,logLevel:r.debug?"DEBUG":"INFO"}),chunk53LJ4W4U_cjs.a.getStatus()==="running"){console.log(u("cli.already_running"));return}let i={};r.port&&(i.port=r.port),r.hostname&&(i.hostname=r.hostname),await chunk53LJ4W4U_cjs.a.start(i);let s=(await chunk53LJ4W4U_cjs.a.get())?.getStatus();Ht({port:s?.port||r.port||8080,hostname:s?.hostname||r.hostname||"localhost",connections:s?.connections||0,mode:chunkJJLKV5TO_cjs.O()?"integrated":"standalone"}),kt();}catch(e){O.error("Failed to start gateway",{error:e instanceof Error?e.message:String(e)}),console.error(`${u("cli.error.start_failed")}: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}}async function le(){O.info("Stopping gateway service");try{if(chunk53LJ4W4U_cjs.a.getStatus()==="stopped"){console.log(u("cli.already_stopped"));return}await chunk53LJ4W4U_cjs.a.stop(),re(),O.info("Gateway stopped successfully");}catch(r){O.error("Failed to stop gateway",{error:r instanceof Error?r.message:String(r)}),console.error(`${u("cli.error.stop_failed")}: ${r instanceof Error?r.message:String(r)}`),process.exit(1);}}async function ce(r){O.info("Restarting gateway service");try{let t={};r.port&&(t.port=r.port),r.hostname&&(t.hostname=r.hostname),await chunk53LJ4W4U_cjs.a.restart(t);let i=(await chunk53LJ4W4U_cjs.a.get())?.getStatus();Ht({port:i?.port||r.port||8080,hostname:i?.hostname||r.hostname||"localhost",connections:i?.connections||0,mode:chunkJJLKV5TO_cjs.O()?"integrated":"standalone"}),kt(),O.info("Gateway restarted successfully");}catch(t){O.error("Failed to restart gateway",{error:t instanceof Error?t.message:String(t)}),console.error(`${u("cli.error.restart_failed")}: ${t instanceof Error?t.message:String(t)}`),process.exit(1);}}function kt(){let r=async t=>{O.debug(`Received ${t}, shutting down gracefully...`),console.log(`
|
|
27
|
-
${u("cli.shutdown_signal",{vars:{signal:t}})}`);try{await
|
|
26
|
+
`);}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(n=>e.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"));}};function pt(r){return r.map(t=>{if(!t.startsWith("--inspect"))return t;let e,i="127.0.0.1",n="9229",s;return (s=t.match(/^(--inspect(-brk)?)$/))!==null?e=s[1]:(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(e=s[1],/^\d+$/.test(s[3])?n=s[3]:i=s[3]):(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(e=s[1],i=s[3],n=s[4]),e&&n!=="0"?`${e}=${i}:${parseInt(n)+1}`:t})}function Y(){if(m.env.NO_COLOR||m.env.FORCE_COLOR==="0"||m.env.FORCE_COLOR==="false")return false;if(m.env.FORCE_COLOR||m.env.CLICOLOR_FORCE!==void 0)return true}Z.Command=J;Z.useColor=Y;});var _t=chunkXQVVSJRM_cjs.c(C=>{chunkSIOB4FC7_cjs.a();var{Argument:mt}=H(),{Command:Q}=dt(),{CommanderError:Ut,InvalidArgumentError:ft}=v(),{Help:zt}=q(),{Option:gt}=z();C.program=new Q;C.createCommand=r=>new Q(r);C.createOption=(r,t)=>new gt(r,t);C.createArgument=(r,t)=>new mt(r,t);C.Command=Q;C.Option=gt;C.Argument=mt;C.Help=zt;C.CommanderError=Ut;C.InvalidArgumentError=ft;C.InvalidOptionArgumentError=ft;});chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var Ot=chunkXQVVSJRM_cjs.d(_t(),1),{program:Se,createCommand:ve,createArgument:$e,createOption:Te,CommanderError:He,InvalidArgumentError:ke,InvalidOptionArgumentError:Ge,Command:yt,Argument:Ve,Option:Le,Help:Ie}=Ot.default;chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var Ct={languages:[{value:"zh-CN",name:"\u7B80\u4F53\u4E2D\u6587",example:"\u4F60\u597D\uFF0CEASBOT\uFF01",supported:true},{value:"en-US",name:"English (United States)",example:"Hello, EASBOT!",supported:true}]};var Xt=Ct.languages,Jt=Xt.filter(r=>r.supported).map(r=>r.value),A={defaultLocale:"zh-CN",locales:Jt},$={},G=(r,t)=>{let e=$[r]||{translation:{}};return $[r]={translation:{...e.translation,...t.translation}},$[r]},V=(r=A.defaultLocale)=>($[r]||G(r,{translation:{}}),{locale:r,resources:$[r]||{translation:{}}});chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var Yt={translation:{"cli.startup.title":"Gateway WebSocket \u670D\u52A1\u5DF2\u542F\u52A8","cli.startup.status":"\u72B6\u6001","cli.startup.port":"\u7AEF\u53E3","cli.startup.hostname":"\u4E3B\u673A\u5730\u5740","cli.startup.protocol":"\u534F\u8BAE","cli.startup.connections":"\u8FDE\u63A5\u6570","cli.startup.running":"\u8FD0\u884C\u4E2D","cli.startup.stopped":"\u5DF2\u505C\u6B62","cli.startup.mode":"\u6A21\u5F0F","cli.startup.mode_standalone":"\u72EC\u7ACB\u6A21\u5F0F","cli.startup.mode_integrated":"\u96C6\u6210\u6A21\u5F0F","cli.status.title":"Gateway WebSocket \u670D\u52A1\u72B6\u6001","cli.stop.title":"Gateway WebSocket \u670D\u52A1\u5DF2\u505C\u6B62","cli.already_running":"Gateway \u670D\u52A1\u5DF2\u5728\u8FD0\u884C\u4E2D","cli.already_stopped":"Gateway \u670D\u52A1\u5DF2\u505C\u6B62","cli.shutdown_signal":"\u6536\u5230 {{signal}}\uFF0C\u6B63\u5728\u4F18\u96C5\u5173\u95ED...","cli.shutdown_success":"Gateway \u670D\u52A1\u5DF2\u6210\u529F\u505C\u6B62","cli.unknown_command":"\u672A\u77E5\u547D\u4EE4: {{command}}","cli.error.start_failed":"\u542F\u52A8 Gateway \u5931\u8D25","cli.error.stop_failed":"\u505C\u6B62 Gateway \u5931\u8D25","cli.error.restart_failed":"\u91CD\u542F Gateway \u5931\u8D25","cli.error.status_failed":"\u83B7\u53D6 Gateway \u72B6\u6001\u5931\u8D25","cli.error.shutdown":"\u5173\u95ED\u65F6\u53D1\u751F\u9519\u8BEF","cli.error.execution_failed":"CLI \u6267\u884C\u5931\u8D25","cli.error.detail":"\u9519\u8BEF\u8BE6\u60C5:","cli.command.start.desc":"\u542F\u52A8 Gateway WebSocket \u670D\u52A1","cli.command.stop.desc":"\u505C\u6B62 Gateway \u670D\u52A1","cli.command.restart.desc":"\u91CD\u542F Gateway \u670D\u52A1","cli.command.status.desc":"\u67E5\u770B Gateway \u670D\u52A1\u72B6\u6001","cli.option.directory":"\u5DE5\u4F5C\u76EE\u5F55","cli.option.port":"\u670D\u52A1\u7AEF\u53E3","cli.option.hostname":"\u4E3B\u673A\u5730\u5740","cli.option.debug":"\u542F\u7528\u8C03\u8BD5\u6A21\u5F0F","cli.help.command":"\u663E\u793A\u5E2E\u52A9\u4FE1\u606F","cli.program.description":"Gateway WebSocket \u670D\u52A1\u7BA1\u7406 CLI","cli.examples.title":"\u793A\u4F8B","cli.example.start":"\u542F\u52A8\u670D\u52A1","cli.example.stop":"\u505C\u6B62\u670D\u52A1","cli.example.restart":"\u91CD\u542F\u670D\u52A1","cli.example.hostname":"\u6307\u5B9A\u76D1\u542C\u5730\u5740"}},wt=Yt;chunkSIOB4FC7_cjs.a();var Zt={translation:{"cli.startup.title":"Gateway WebSocket Server Started","cli.startup.status":"Status","cli.startup.port":"Port","cli.startup.hostname":"Hostname","cli.startup.protocol":"Protocol","cli.startup.connections":"Connections","cli.startup.running":"Running","cli.startup.stopped":"Stopped","cli.startup.mode":"Mode","cli.startup.mode_standalone":"Standalone","cli.startup.mode_integrated":"Integrated","cli.status.title":"Gateway WebSocket Server Status","cli.stop.title":"Gateway WebSocket Server Stopped","cli.already_running":"Gateway server is already running.","cli.already_stopped":"Gateway server is already stopped.","cli.shutdown_signal":"Received {{signal}}, shutting down gracefully...","cli.shutdown_success":"Gateway stopped successfully.","cli.unknown_command":"Unknown command: {{command}}","cli.error.start_failed":"Failed to start gateway","cli.error.stop_failed":"Failed to stop gateway","cli.error.restart_failed":"Failed to restart gateway","cli.error.status_failed":"Failed to get gateway status","cli.error.shutdown":"Error during shutdown","cli.error.execution_failed":"CLI failed to execute","cli.error.detail":"Error detail:","cli.command.start.desc":"Start Gateway WebSocket service","cli.command.stop.desc":"Stop Gateway service","cli.command.restart.desc":"Restart Gateway service","cli.command.status.desc":"Check Gateway service status","cli.option.directory":"Working directory","cli.option.port":"Service port","cli.option.hostname":"Host address","cli.option.debug":"Enable debug mode","cli.help.command":"Display help information","cli.program.description":"Gateway WebSocket service management CLI","cli.examples.title":"Examples","cli.example.start":"Start service","cli.example.stop":"Stop service","cli.example.restart":"Restart service","cli.example.hostname":"Specify listening address"}},bt=Zt;var Qt=()=>{V("zh-CN"),V("en-US"),G("zh-CN",wt),G("en-US",bt);};Qt();var tt=new Map;var et=new Map;var te=r=>{if(et.has(r))return et.get(r);let t=/{{\s*(\w+)\s*}}/g,e=[],i;for(;(i=t.exec(r))!==null;){let o=i[1];o&&!e.includes(o)&&e.push(o);}let n=new RegExp("{{\\s*("+e.join("|")+")\\s*}}","g"),s={keys:e,regex:n};return et.set(r,s),s},xt=(r,t)=>{if(!r||typeof r!="string")return "";if(!t||Object.keys(t).length===0)return r;let{regex:e,keys:i}=te(r);return i.length===0||!i.some(s=>s in t)?r:r.replace(e,(s,o)=>{let a=t[o];return a==null?"":String(a)})},ee=r=>r&&A.locales.includes(r)?r:A.defaultLocale,At=r=>{if(!tt.has(r)){let{resources:t}=V(r);tt.set(r,t);}return tt.get(r)},ie=(r,t={})=>{let e=ee(t.locale),n=At(e)?.translation[r];if(n&&typeof n=="string"){let s=xt(n,t.vars);return s!=null?String(s):String(r)}if(e!==A.defaultLocale){let o=At(A.defaultLocale)?.translation[r];if(o&&typeof o=="string"){let a=xt(o,t.vars);return a!=null?String(a):String(r)}}return String(t.fallback??r)},u=ie;chunkSIOB4FC7_cjs.a();var O=chunkEKLLH53Y_cjs.a.create({service:"cli-gateway"}),I=58,Et="\u2551",St="\u2554",vt="\u255A",$t="\u2560",it="\u2550";function se(r,t=I){let e=t-r.length;return e<=0?r:r+" ".repeat(e)}function _(r){console.log(`${Et} ${se(r)} ${Et}`);}function nt(){console.log(`${St}${it.repeat(I)}${St.replace("\u2554","\u2557")}`);}function Tt(){console.log(`${$t}${it.repeat(I)}${$t.replace("\u2560","\u2563")}`);}function st(){console.log(`${vt}${it.repeat(I)}${vt.replace("\u255A","\u255D")}`);}function Ht(r){console.log(""),nt(),_(u("cli.startup.title")),Tt(),_(`${u("cli.startup.status")}: ${u("cli.startup.running").padEnd(37-u("cli.startup.status").length)}`),_(`${u("cli.startup.port")}: ${String(r.port).padEnd(37-u("cli.startup.port").length)}`),_(`${u("cli.startup.hostname")}: ${r.hostname.padEnd(37-u("cli.startup.hostname").length)}`),_(`${u("cli.startup.protocol")}: ws${" ".repeat(32)}`),r.connections!==void 0&&_(`${u("cli.startup.connections")}:${String(r.connections).padEnd(37-u("cli.startup.connections").length)}`),_(`${u("cli.startup.mode")}: ${(r.mode==="standalone"?u("cli.startup.mode_standalone"):u("cli.startup.mode_integrated")).padEnd(37-u("cli.startup.mode").length)}`),st(),console.log("");}function re(){console.log(""),nt(),_(u("cli.stop.title")),st(),console.log("");}async function oe(){try{let r=chunkEOLBEWUW_cjs.a.getStatus(),e=(await chunkEOLBEWUW_cjs.a.get())?.getStatus();console.log(""),nt(),_(u("cli.status.title")),Tt(),_(`${u("cli.startup.status")}: ${r.toUpperCase().padEnd(37-u("cli.startup.status").length)}`),e&&(_(`${u("cli.startup.port")}: ${String(e.port).padEnd(37-u("cli.startup.port").length)}`),_(`${u("cli.startup.hostname")}: ${(e.hostname||"localhost").padEnd(37-u("cli.startup.hostname").length)}`),_(`${u("cli.startup.connections")}:${String(e.connections||0).padEnd(37-u("cli.startup.connections").length)}`)),st(),console.log("");}catch(r){O.error("Failed to get gateway status",{error:r instanceof Error?r.message:String(r)}),console.error(`${u("cli.error.status_failed")}: ${r instanceof Error?r.message:String(r)}`),process.exit(1);}}async function ae(r){let t=r.directory||process.cwd();O.info("Starting gateway service",{port:r.port,hostname:r.hostname,directory:t});try{if(await chunkEOLBEWUW_cjs.a.init({directory:t,printLogs:r.debug,logLevel:r.debug?"DEBUG":"INFO"}),chunkEOLBEWUW_cjs.a.getStatus()==="running"){console.log(u("cli.already_running"));return}let i={};r.port&&(i.port=r.port),r.hostname&&(i.hostname=r.hostname),await chunkEOLBEWUW_cjs.a.start(i);let s=(await chunkEOLBEWUW_cjs.a.get())?.getStatus();Ht({port:s?.port||r.port||8080,hostname:s?.hostname||r.hostname||"localhost",connections:s?.connections||0,mode:chunkEKLLH53Y_cjs.O()?"integrated":"standalone"}),kt();}catch(e){O.error("Failed to start gateway",{error:e instanceof Error?e.message:String(e)}),console.error(`${u("cli.error.start_failed")}: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}}async function le(){O.info("Stopping gateway service");try{if(chunkEOLBEWUW_cjs.a.getStatus()==="stopped"){console.log(u("cli.already_stopped"));return}await chunkEOLBEWUW_cjs.a.stop(),re(),O.info("Gateway stopped successfully");}catch(r){O.error("Failed to stop gateway",{error:r instanceof Error?r.message:String(r)}),console.error(`${u("cli.error.stop_failed")}: ${r instanceof Error?r.message:String(r)}`),process.exit(1);}}async function ce(r){O.info("Restarting gateway service");try{let t={};r.port&&(t.port=r.port),r.hostname&&(t.hostname=r.hostname),await chunkEOLBEWUW_cjs.a.restart(t);let i=(await chunkEOLBEWUW_cjs.a.get())?.getStatus();Ht({port:i?.port||r.port||8080,hostname:i?.hostname||r.hostname||"localhost",connections:i?.connections||0,mode:chunkEKLLH53Y_cjs.O()?"integrated":"standalone"}),kt(),O.info("Gateway restarted successfully");}catch(t){O.error("Failed to restart gateway",{error:t instanceof Error?t.message:String(t)}),console.error(`${u("cli.error.restart_failed")}: ${t instanceof Error?t.message:String(t)}`),process.exit(1);}}function kt(){let r=async t=>{O.debug(`Received ${t}, shutting down gracefully...`),console.log(`
|
|
27
|
+
${u("cli.shutdown_signal",{vars:{signal:t}})}`);try{await chunkEOLBEWUW_cjs.a.stop(),O.debug("Gateway stopped"),console.log(u("cli.shutdown_success"));}catch(e){O.error("Error during shutdown",{error:e instanceof Error?e.message:String(e)});}process.exit(0);};process.on("SIGINT",()=>{r("SIGINT").catch(console.error);}),process.on("SIGTERM",()=>{r("SIGTERM").catch(console.error);});}async function L(r,t){switch(r){case "start":await ae(t);break;case "stop":await le();break;case "restart":await ce(t);break;case "status":await oe();break;default:console.error(u("cli.unknown_command",{vars:{command:r}})),process.exit(1);}}function ue(r){r.command("start").description(u("cli.command.start.desc")).option("-D, --directory <path>",u("cli.option.directory")).option("-p, --port <number>",u("cli.option.port"),t=>parseInt(t,10)).option("-H, --hostname <address>",u("cli.option.hostname")).option("-d, --debug",u("cli.option.debug"),false).action(async t=>{await L("start",{directory:t.directory,port:t.port,hostname:t.hostname,debug:t.debug});}),r.command("stop").description(u("cli.command.stop.desc")).action(async()=>{await L("stop",{});}),r.command("restart").description(u("cli.command.restart.desc")).option("-D, --directory <path>",u("cli.option.directory")).option("-p, --port <number>",u("cli.option.port"),t=>parseInt(t,10)).option("-H, --hostname <address>",u("cli.option.hostname")).option("-d, --debug",u("cli.option.debug"),false).action(async t=>{await L("restart",{directory:t.directory,port:t.port,hostname:t.hostname,debug:t.debug});}),r.command("status").description(u("cli.command.status.desc")).action(async()=>{await L("status",{});}),r.addHelpCommand("help",u("cli.help.command")).addHelpText("after",`
|
|
28
28
|
|
|
29
29
|
${u("cli.examples.title")}:
|
|
30
30
|
$ gateway start --port 8080 # ${u("cli.example.start")}
|
package/dist/cli.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a as a$3}from'./chunks/chunk-
|
|
1
|
+
import {a as a$3}from'./chunks/chunk-J2DSTELL.mjs';import {a as a$2,O as O$1}from'./chunks/chunk-ETYFY7SI.mjs';import {a}from'./chunks/chunk-SJNPXLNN.mjs';import {c,a as a$1,d}from'./chunks/chunk-TY6W6O7O.mjs';import {loadEnv}from'@easbot/utils';var $=c(R=>{a();var H=class extends Error{constructor(t,e,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0;}},F=class extends H{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name;}};R.CommanderError=H;R.InvalidArgumentError=F;});var k=c(N=>{a();var{InvalidArgumentError:Lt}=$(),D=class{constructor(t,e){switch(this.description=e||"",this.variadic=false,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case "<":this.required=true,this._name=t.slice(1,-1);break;case "[":this.required=false,this._name=t.slice(1,-1);break;default:this.required=true,this._name=t;break}this._name.endsWith("...")&&(this.variadic=true,this._name=this._name.slice(0,-3));}name(){return this._name}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new Lt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}argRequired(){return this.required=true,this}argOptional(){return this.required=false,this}};function It(r){let t=r.name()+(r.variadic===true?"...":"");return r.required?"<"+t+">":"["+t+"]"}N.Argument=D;N.humanReadableArgName=It;});var j=c(q=>{a();var{humanReadableArgName:Wt}=k(),M=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=false,this.sortOptions=false,this.showGlobalOptions=false;}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80;}visibleCommands(t){let e=t.commands.filter(n=>!n._hidden),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort((n,s)=>n.name().localeCompare(s.name())),e}compareOptions(t,e){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter(n=>!n.hidden),i=t._getHelpOption();if(i&&!i.hidden){let n=i.short&&t._findOption(i.short),s=i.long&&t._findOption(i.long);!n&&!s?e.push(i):i.long&&!s?e.push(t.createOption(i.long,i.description)):i.short&&!n&&e.push(t.createOption(i.short,i.description));}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return [];let e=[];for(let i=t.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);e.push(...n);}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||"";}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(i=>Wt(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(n)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(n)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let n=t.parent;n;n=n.parent)i=n.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatItemList(t,e,i){return e.length===0?[]:[i.styleTitle(t),...e,""]}groupItems(t,e,i){let n=new Map;return t.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]);}),e.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]),n.get(o).push(s);}),n}formatHelp(t,e){let i=e.padWidth(t,e),n=e.helpWidth??80;function s(c,d){return e.formatItem(c,i,d,e)}let o=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],a=e.commandDescription(t);a.length>0&&(o=o.concat([e.boxWrap(e.styleCommandDescription(a),n),""]));let h=e.visibleArguments(t).map(c=>s(e.styleArgumentTerm(e.argumentTerm(c)),e.styleArgumentDescription(e.argumentDescription(c))));if(o=o.concat(this.formatItemList("Arguments:",h,e)),this.groupItems(t.options,e.visibleOptions(t),c=>c.helpGroupHeading??"Options:").forEach((c,d)=>{let S=c.map(x=>s(e.styleOptionTerm(e.optionTerm(x)),e.styleOptionDescription(e.optionDescription(x))));o=o.concat(this.formatItemList(d,S,e));}),e.showGlobalOptions){let c=e.visibleGlobalOptions(t).map(d=>s(e.styleOptionTerm(e.optionTerm(d)),e.styleOptionDescription(e.optionDescription(d))));o=o.concat(this.formatItemList("Global Options:",c,e));}return this.groupItems(t.commands,e.visibleCommands(t),c=>c.helpGroup()||"Commands:").forEach((c,d)=>{let S=c.map(x=>s(e.styleSubcommandTerm(e.subcommandTerm(x)),e.styleSubcommandDescription(e.subcommandDescription(x))));o=o.concat(this.formatItemList(d,S,e));}),o.join(`
|
|
2
2
|
`)}displayWidth(t){return at(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e==="[command]"?this.styleSubcommandText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleCommandText(e)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleSubcommandText(e)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}preformatted(t){return /\n[^\S\r\n]/.test(t)}formatItem(t,e,i,n){let o=" ".repeat(2);if(!i)return o+t;let a=t.padEnd(e+t.length-n.displayWidth(t)),h=2,l=(this.helpWidth??80)-e-h-2,c;return l<this.minWidthToWrap||n.preformatted(i)?c=i:c=n.boxWrap(i,l).replace(/\n/g,`
|
|
3
3
|
`+" ".repeat(e+h)),o+a+" ".repeat(h)+c.replace(/\n/g,`
|
|
4
4
|
${o}`)}boxWrap(t,e){if(e<this.minWidthToWrap)return t;let i=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,s=[];return i.forEach(o=>{let a=o.match(n);if(a===null){s.push("");return}let h=[a.shift()],p=this.displayWidth(h[0]);a.forEach(l=>{let c=this.displayWidth(l);if(p+c<=e){h.push(l),p+=c;return}s.push(h.join(""));let d=l.trimStart();h=[d],p=this.displayWidth(d);}),s.push(h.join(""));}),s.join(`
|