HEX
Server: nginx/1.24.0
System: Linux nowruzgan 6.8.0-57-generic #59-Ubuntu SMP PREEMPT_DYNAMIC Sat Mar 15 17:40:59 UTC 2025 x86_64
User: babak (1000)
PHP: 8.3.6
Disabled: NONE
Upload Files
File: /var/dev/nowruzgan/travelogue/node_modules/stdin-discarder/index.js
import process from 'node:process';

const ASCII_ETX_CODE = 0x03; // Ctrl+C emits this code

class StdinDiscarder {
	#activeCount = 0;

	start() {
		this.#activeCount++;

		if (this.#activeCount === 1) {
			this.#realStart();
		}
	}

	stop() {
		if (this.#activeCount <= 0) {
			throw new Error('`stop` called more times than `start`');
		}

		this.#activeCount--;

		if (this.#activeCount === 0) {
			this.#realStop();
		}
	}

	#realStart() {
		// No known way to make it work reliably on Windows.
		if (process.platform === 'win32' || !process.stdin.isTTY) {
			return;
		}

		process.stdin.setRawMode(true);
		process.stdin.on('data', this.#handleInput);
		process.stdin.resume();
	}

	#realStop() {
		if (!process.stdin.isTTY) {
			return;
		}

		process.stdin.off('data', this.#handleInput);
		process.stdin.pause();
		process.stdin.setRawMode(false);
	}

	#handleInput(chunk) {
		// Allow Ctrl+C to gracefully exit.
		if (chunk[0] === ASCII_ETX_CODE) {
			process.emit('SIGINT');
		}
	}
}

const stdinDiscarder = new StdinDiscarder();

export default stdinDiscarder;