11import { spawn } from 'child_process' ;
22import {
3+ CORTEX_JS_STOP_API_SERVER_URL ,
34 defaultCortexJsHost ,
45 defaultCortexJsPort ,
56} from '@/infrastructure/constants/cortex' ;
@@ -9,6 +10,7 @@ import { join } from 'path';
910type ServeOptions = {
1011 host ?: string ;
1112 port ?: number ;
13+ attach : boolean ;
1214} ;
1315
1416@SubCommand ( {
@@ -20,7 +22,25 @@ export class ServeCommand extends CommandRunner {
2022 const host = options ?. host || defaultCortexJsHost ;
2123 const port = options ?. port || defaultCortexJsPort ;
2224
23- spawn (
25+ if ( _input [ 0 ] === 'stop' ) {
26+ return this . stopServer ( ) . then ( ( ) => console . log ( 'API server stopped' ) ) ;
27+ } else {
28+ return this . startServer ( host , port , options ) ;
29+ }
30+ }
31+
32+ private async stopServer ( ) {
33+ return fetch ( CORTEX_JS_STOP_API_SERVER_URL ( ) , {
34+ method : 'DELETE' ,
35+ } ) . catch ( ( ) => { } ) ;
36+ }
37+
38+ private async startServer (
39+ host : string ,
40+ port : number ,
41+ options : ServeOptions = { attach : true } ,
42+ ) {
43+ const serveProcess = spawn (
2444 'node' ,
2545 process . env . TEST
2646 ? [ join ( __dirname , '../../../dist/src/main.js' ) ]
@@ -32,10 +52,14 @@ export class ServeCommand extends CommandRunner {
3252 CORTEX_JS_PORT : port . toString ( ) ,
3353 NODE_ENV : 'production' ,
3454 } ,
35- stdio : 'inherit' ,
36- detached : false ,
55+ stdio : options ?. attach ? 'inherit' : 'ignore ',
56+ detached : true ,
3757 } ,
3858 ) ;
59+ if ( ! options ?. attach ) {
60+ serveProcess . unref ( ) ;
61+ console . log ( 'Started server at http://%s:%d' , host , port ) ;
62+ }
3963 }
4064
4165 @Option ( {
@@ -53,4 +77,14 @@ export class ServeCommand extends CommandRunner {
5377 parsePort ( value : string ) {
5478 return parseInt ( value , 10 ) ;
5579 }
80+
81+ @Option ( {
82+ flags : '-a, --attach' ,
83+ description : 'Attach to interactive chat session' ,
84+ defaultValue : false ,
85+ name : 'attach' ,
86+ } )
87+ parseAttach ( ) {
88+ return true ;
89+ }
5690}
0 commit comments