| 46 | } |
| 47 | |
| 48 | export class Process extends Async(class Process extends ProcessEvents { |
| 49 | #process: ChildProcess; |
| 50 | |
| 51 | readonly stdio: ReadWriteLineStream; |
| 52 | readonly error: ReadableLineStream; |
| 53 | |
| 54 | get active() { |
| 55 | return !this.exitCode.isCompleted; |
| 56 | } |
| 57 | |
| 58 | get name() { |
| 59 | return basename(this.executable); |
| 60 | } |
| 61 | |
| 62 | get pid() { |
| 63 | return this.#process.pid; |
| 64 | } |
| 65 | |
| 66 | /** Event signals when the process is being launched */ |
| 67 | started = this.newNotification(notifications.started, { now: true, once: true }); |
| 68 | |
| 69 | /** Event signals when the process has stopped */ |
| 70 | exited = this.newNotification<number>(notifications.exited, { now: true, once: true }); |
| 71 | |
| 72 | exitCode = new ManualPromise<number>(); |
| 73 | init: Promise<void> | undefined; |
| 74 | |
| 75 | constructor(readonly executable: string, readonly args: Primitive[], readonly cwd = process.cwd(), readonly env = process.env, stdInOpen = true, ...subscribers: ArbitraryObject[]) { |
| 76 | super(); |
| 77 | // add any subscribers to the process events before anything else happens |
| 78 | this.subscribe(...subscribers); |
| 79 | |
| 80 | let spawned = false; |
| 81 | executable = resolve(executable); // ensure that slashes are correct -- if they aren't, cmd.exe itself fails when slashes are wrong. (other apps don't necessarily fail, but cmd.exe does) |
| 82 | |
| 83 | const startTime = Date.now(); |
| 84 | verbose(`Starting '${this.name}' ${args.map((each) => each.toString()).join(' ')}`); |
| 85 | const process = this.#process = spawn(executable, args.map((each) => each.toString()), { cwd, env, stdio: [stdInOpen ? 'pipe' : null, 'pipe', 'pipe'], shell: false }). |
| 86 | on('error', (err: Error) => { |
| 87 | this.exitCode.reject(err); |
| 88 | }). |
| 89 | on('spawn', () => { |
| 90 | spawned = true; |
| 91 | void this.started(); |
| 92 | }). |
| 93 | on('close', (code: number, signal: NodeJS.Signals) => { |
| 94 | this.exitCode.resolve(code); |
| 95 | |
| 96 | if (spawned) { |
| 97 | // ensure the streams are completely closed before we emit the exited event |
| 98 | finalize(this.stdio); |
| 99 | finalize(this.error); |
| 100 | } |
| 101 | |
| 102 | verbose(`Ending '${this.name}' ${args.map((each) => each.toString()).join(' ')} // exiting with code ${code}. in ${Date.now() - startTime}ms}`); |
| 103 | |
| 104 | this.exited(code ?? (signal as any)); |
| 105 | }); |