Skip to content

Input

The input module decodes raw terminal bytes into structured events. All parsing logic lives in WASM. The TypeScript layer is a thin wrapper. See Architecture for why parsing is pure computation and reading stdin is up to you.

Creates an input parser instance.

import {
function createInput(options?: InputOptions): Promise<Input>
createInput
} from "@bomb.sh/tty";
async function
function main(): Promise<void>
main
() {
let
let input: Input
input
= await
function createInput(options?: InputOptions): Promise<Input>
createInput
({
InputOptions.escLatency?: number

Milliseconds to wait before resolving a lone ESC byte as the Escape key rather than the start of an escape sequence. Lower values feel snappier but risk misinterpreting sequences on slow connections.

For reference, Vim's ttimeoutlen defaults to 100ms and ncurses ESCDELAY defaults to 1000ms. The default of 25ms is tuned for local terminals where escape sequences arrive within microseconds.

@default25

escLatency
: 25 });
}
OptionTypeDefaultDescription
escLatencynumber25Milliseconds to wait before resolving a lone ESC as the Escape key
terminfoUint8Arrayxterm defaultsCompiled terminfo binary for terminal-specific sequences

Feed raw bytes from stdin and return parsed events. Call with no arguments to flush a pending ESC after the latency period.

import {
function createInput(options?: InputOptions): Promise<Input>
createInput
} from "@bomb.sh/tty";
async function
function main(): Promise<void>
main
() {
let
let input: Input
input
= await
function createInput(options?: InputOptions): Promise<Input>
createInput
({
InputOptions.escLatency?: number

Milliseconds to wait before resolving a lone ESC byte as the Escape key rather than the start of an escape sequence. Lower values feel snappier but risk misinterpreting sequences on slow connections.

For reference, Vim's ttimeoutlen defaults to 100ms and ncurses ESCDELAY defaults to 1000ms. The default of 25ms is tuned for local terminals where escape sequences arrive within microseconds.

@default25

escLatency
: 25 });
var process: NodeJS.Process
process
.
NodeJS.Process.stdin: NodeJS.ReadStream & {
fd: 0;
}

The process.stdin property returns a stream connected tostdin (fd 0). It is a net.Socket (which is a Duplex stream) unless fd 0 refers to a file, in which case it is a Readable stream.

For details of how to read from stdin see readable.read().

As a Duplex stream, process.stdin can also be used in "old" mode that is compatible with scripts written for Node.js prior to v0.10. For more information see Stream compatibility.

In "old" streams mode the stdin stream is paused by default, so one must call process.stdin.resume() to read from it. Note also that calling process.stdin.resume() itself would switch stream to "old" mode.

stdin
.
ReadStream.setRawMode(mode: boolean): NodeJS.ReadStream & {
fd: 0;
}

Allows configuration of tty.ReadStream so that it operates as a raw device.

When in raw mode, input is always available character-by-character, not including modifiers. Additionally, all special processing of characters by the terminal is disabled, including echoing input characters. Ctrl+C will no longer cause a SIGINT when in this mode.

@sincev0.7.7

@parammode If true, configures the tty.ReadStream to operate as a raw device. If false, configures the tty.ReadStream to operate in its default mode. The readStream.isRaw property will be set to the resulting mode.

setRawMode
(true);
let
let timer: NodeJS.Timeout | undefined
timer
:
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any

Obtain the return type of a function type

ReturnType
<typeof
function setTimeout<TArgs extends any[]>(callback: (...args: TArgs) => void, delay?: number, ...args: TArgs): NodeJS.Timeout (+1 overload)

Schedules execution of a one-time callback after delay milliseconds.

The callback will likely not be invoked in precisely delay milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified.

When delay is larger than 2147483647 or less than 1 or NaN, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setTimeout().

@sincev0.0.1

@paramcallback The function to call when the timer elapses.

@paramdelay The number of milliseconds to wait before calling the callback. Default: 1.

@paramargs Optional arguments to pass when the callback is called.

@returnsfor use with clearTimeout()

setTimeout
> | undefined;
var process: NodeJS.Process
process
.
NodeJS.Process.stdin: NodeJS.ReadStream & {
fd: 0;
}

The process.stdin property returns a stream connected tostdin (fd 0). It is a net.Socket (which is a Duplex stream) unless fd 0 refers to a file, in which case it is a Readable stream.

For details of how to read from stdin see readable.read().

As a Duplex stream, process.stdin can also be used in "old" mode that is compatible with scripts written for Node.js prior to v0.10. For more information see Stream compatibility.

In "old" streams mode the stdin stream is paused by default, so one must call process.stdin.resume() to read from it. Note also that calling process.stdin.resume() itself would switch stream to "old" mode.

stdin
.
Socket.on(event: "data", listener: (data: NonSharedBuffer) => void): NodeJS.ReadStream & {
fd: 0;
} (+12 overloads)

Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

server.on('connection', (stream) => {
console.log('someone connected!');
});

Returns a reference to the EventEmitter, so that calls can be chained.

By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a

on
("data", (
buf: NonSharedBuffer
buf
) => {
function clearTimeout(timeout: NodeJS.Timeout | string | number | undefined): void

Cancels a Timeout object created by setTimeout().

@sincev0.0.1

@paramtimeout A Timeout object as returned by setTimeout() or the primitive of the Timeout object as a string or a number.

clearTimeout
(
let timer: NodeJS.Timeout | undefined
timer
);
let {
let events: InputEvent[]
events
,
let pending: {
delay: number;
} | undefined
pending
} =
let input: Input
input
.
Input.scan(bytes?: Uint8Array): ScanResult

Feed raw bytes from stdin into the parser and return any events produced. Call with no arguments to flush a pending ESC after the latency period has elapsed.

@example

let { events, pending } = input.scan(bytes);
for (let event of events) {
dispatch(event);
}
if (pending) {
// there is a pending ESC event. wait for the delay
await sleep(pending.delay);
// re-scan
let flush = input.scan();
//dispatch the flushed ESC
for (let event of flush.events) {
dispatch(event)
}
}

scan
(new
var Uint8Array: Uint8ArrayConstructor
new (elements: Iterable<number>) => Uint8Array<ArrayBuffer> (+6 overloads)
Uint8Array
(
buf: NonSharedBuffer
buf
));
for (let
let event: InputEvent
event
of
let events: InputEvent[]
events
) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
let event: InputEvent
event
);
}
if (
let pending: {
delay: number;
} | undefined
pending
) {
let timer: NodeJS.Timeout | undefined
timer
=
function setTimeout<[]>(callback: () => void, delay?: number): NodeJS.Timeout (+1 overload)

Schedules execution of a one-time callback after delay milliseconds.

The callback will likely not be invoked in precisely delay milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified.

When delay is larger than 2147483647 or less than 1 or NaN, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setTimeout().

@sincev0.0.1

@paramcallback The function to call when the timer elapses.

@paramdelay The number of milliseconds to wait before calling the callback. Default: 1.

@paramargs Optional arguments to pass when the callback is called.

@returnsfor use with clearTimeout()

setTimeout
(() => {
let
let flush: ScanResult
flush
=
let input: Input
input
.
Input.scan(bytes?: Uint8Array): ScanResult

Feed raw bytes from stdin into the parser and return any events produced. Call with no arguments to flush a pending ESC after the latency period has elapsed.

@example

let { events, pending } = input.scan(bytes);
for (let event of events) {
dispatch(event);
}
if (pending) {
// there is a pending ESC event. wait for the delay
await sleep(pending.delay);
// re-scan
let flush = input.scan();
//dispatch the flushed ESC
for (let event of flush.events) {
dispatch(event)
}
}

scan
();
for (let
let event: InputEvent
event
of
let flush: ScanResult
flush
.
ScanResult.events: InputEvent[]
events
) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
let event: InputEvent
event
);
}
},
let pending: {
delay: number;
}
pending
.
delay: number
delay
);
}
});
}
PropertyTypeDescription
eventsInputEvent[]Events produced from this scan
pending{ delay: number }Present when a lone ESC is buffered. Re-call scan() after delay ms
TypeDescription
keydownKey was pressed
keyrepeatKey auto-repeat (Kitty enhancement level 2+)
keyupKey was released (Kitty enhancement level 2+)

All keyboard events include:

PropertyTypeDescription
keystringKey value (e.g. "a", "Enter", "ArrowUp")
codeKeyCodePhysical key identity (US PC-101 layout)
textstring?Typed character, if applicable
shiftedstring?Shifted character variant
alt, ctrl, shifttrue?Modifier keys held
TypeDescription
mousedownButton pressed (left, right, middle)
mouseupButton released
mousemoveMovement while button held
wheelScroll wheel (direction: "up" | "down")

Mouse events include x and y coordinates (0-based) and optional modifiers.

TypeDescription
resizeTerminal resized. Returns { width, height }
cursorDSR cursor position report. Returns { row, column } (1-based)

Pointer events (pointerenter, pointerleave, pointerclick) are produced by the renderer, not the input parser.

The parser recognizes:

  • VT/ANSI escape sequences
  • UTF-8 codepoints
  • Mouse protocols (VT200, SGR, urxvt)
  • Progressive keyboard protocol (via settings)
  • Partial sequence reassembly across read boundaries
  • Settings API (enable mouse tracking and keyboard protocols)
  • Term API (pointer hit testing on the render side)