@@ -98,6 +98,45 @@ export function getChildProcessEnv(): NodeJS.ProcessEnv {
9898 return safeEnv ;
9999}
100100
101+ export function validatePath ( filePath : string ) : { valid : boolean ; error ?: string ; absolutePath ?: string } {
102+ if ( ! filePath || typeof filePath !== 'string' ) {
103+ return { valid : false , error : 'Path is empty' } ;
104+ }
105+ if ( ! path . isAbsolute ( filePath ) ) {
106+ return { valid : false , error : `Path must be absolute: ${ filePath } ` } ;
107+ }
108+ return { valid : true , absolutePath : path . normalize ( filePath ) } ;
109+ }
110+
111+ function withTimeout < T > ( p : Promise < T > , ms : number , label : string ) : Promise < T > {
112+ let timer : NodeJS . Timeout | undefined ;
113+ p . catch ( ( ) => { /* 防止 race 失败方触发 unhandledRejection */ } ) ;
114+ return Promise . race ( [
115+ p ,
116+ new Promise < T > ( ( _ , reject ) => {
117+ timer = setTimeout ( ( ) => reject ( Object . assign ( new Error ( `${ label } timed out (${ ms } ms)` ) , { code : 'ETIMEDOUT' } ) ) , ms ) ;
118+ } ) ,
119+ ] ) . finally ( ( ) => { if ( timer ) clearTimeout ( timer ) ; } ) ;
120+ }
121+
122+ export async function resolveWorkingDir ( workingDir : string | undefined ) : Promise < { cwd ?: string ; error ?: string } > {
123+ if ( ! workingDir ) return { error : 'workingDir is required' } ;
124+
125+ const v = validatePath ( workingDir ) ;
126+ if ( ! v . valid ) return { error : v . error } ;
127+
128+ const cwd = v . absolutePath ! ;
129+ try {
130+ const stat = await withTimeout ( fs . promises . stat ( cwd ) , PROBE_TIMEOUT_MS , `stat ${ cwd } ` ) ;
131+ if ( ! stat . isDirectory ( ) ) return { error : `Path is not a directory: ${ cwd } ` } ;
132+ return { cwd } ;
133+ } catch ( e : any ) {
134+ if ( e ?. code === 'ENOENT' ) return { error : `Working directory not found: ${ cwd } ` } ;
135+ if ( e ?. code === 'ETIMEDOUT' ) return { error : e . message } ;
136+ return { error : `Failed to check working directory: ${ e ?. message ?? e } ` } ;
137+ }
138+ }
139+
101140export async function killProcessTree ( proc : ChildProcess , isExited : ( ) => boolean ) : Promise < void > {
102141 const pid = proc . pid ;
103142 if ( ! pid || isExited ( ) ) return ;
0 commit comments