tprompter
Version:
```bash $ ask anything ```
70 lines (69 loc) • 3.31 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { fork } from 'node:child_process';
import path from 'node:path';
import { InjectLogger } from '../logger/logger.decorator.js';
import chalk from 'chalk';
import { fileURLToPath } from 'node:url';
/**
* Implementation of the StdinDataReader interface that reads data from the standard input.
* The reason why we need StdinDataReader is that Jest doen't support `import.meta.url`
* So we need to mock the `readData` method in tests and avoid any mention of `import.meta.url` and thus mention of this file.
*/
let StdinDataReaderImpl = class StdinDataReaderImpl {
constructor(logger) {
this.logger = logger;
}
readData(placeholder = 'Input required', options = {}) {
if (process.stdin.isTTY && options.onlyPipe) {
this.logger.debug('No data in stdin, skipping');
return Promise.resolve('');
}
return new Promise((resolve, reject) => {
if (process.stdin.isTTY) {
console.log(chalk.green(`❯ Input required (Press CTRL+D or type /EOF to finish):`), placeholder);
}
const dirname = path.dirname(fileURLToPath(import.meta.url));
const childPath = path.join(dirname, 'readData.process.js');
const child = fork(childPath, [], {
stdio: ['inherit', 'pipe', 'pipe', 'ipc'],
});
let errorOutput = '';
child.stderr.on('data', (chunk) => {
errorOutput += chunk;
});
child.on('message', (message) => {
if (!message.data.endsWith('\n')) {
process.stdout.write('\n');
}
resolve(message.data);
});
child.on('close', (code) => {
if (code !== 0) {
this.logger.error(`Child process exited with code ${code}`);
this.logger.error(`Error output: ${errorOutput}`);
reject(new Error(`Child process exited with code ${code}`));
}
});
child.on('error', (err) => {
this.logger.error(`Child process error: ${err}`);
reject(err);
});
});
}
};
StdinDataReaderImpl = __decorate([
__param(0, InjectLogger(StdinDataReaderImpl)),
__metadata("design:paramtypes", [Object])
], StdinDataReaderImpl);
export { StdinDataReaderImpl };