Open History to see the last commit
1/**
2 * Shared Node.js implementation of Effect's `Terminal` service.
3 *
4 * `NodeTerminal` adapts Node's `readline` APIs plus the current process
5 * `stdin` and `stdout` streams into {@link Terminal.Terminal}. The service can
6 * display output, read a line, stream key input, and read terminal dimensions.
7 * `make` manages readline and TTY raw mode in a scope, while `layer` provides
8 * the default service that ends key input on Ctrl+C or Ctrl+D.
9 *
10 * @since 4.0.0
11 */
12import type * as Cause from "effect/Cause"
13import * as Effect from "effect/Effect"
14import * as Layer from "effect/Layer"
15import * as Option from "effect/Option"
16import { badArgument, type PlatformError } from "effect/PlatformError"
17import * as Predicate from "effect/Predicate"
18import * as Queue from "effect/Queue"
19import * as RcRef from "effect/RcRef"
20import type * as Scope from "effect/Scope"
21import * as Terminal from "effect/Terminal"
22import * as readline from "node:readline"
23
24/**
25 * Creates a scoped process-backed `Terminal` using Node `readline`, enabling
26 * TTY raw mode while in scope and using the supplied predicate to decide when
27 * key input should end.
28 *
29 * @category constructors
30 * @since 4.0.0
31 */
32export const make: (
33 shouldQuit?: (input: Terminal.UserInput) => boolean
34) => Effect.Effect<Terminal.Terminal, never, Scope.Scope> = Effect.fnUntraced(
35 function*(shouldQuit: (input: Terminal.UserInput) => boolean = defaultShouldQuit) {
36 const stdin = process.stdin
37 const stdout = process.stdout
38
39 // Acquire readline interface with TTY setup/cleanup inside the scope
40 const rlRef = yield* RcRef.make({
41 acquire: Effect.acquireRelease(
42 Effect.sync(() => {
43 const rl = readline.createInterface({ input: stdin, escapeCodeTimeout: 50 })
44 readline.emitKeypressEvents(stdin, rl)
45
46 if (stdin.isTTY) {
47 stdin.setRawMode(true)
48 }
49 return rl
50 }),
51 (rl) =>
52 Effect.sync(() => {
53 if (stdin.isTTY) {
54 stdin.setRawMode(false)
55 }
56 rl.close()
57 })
58 )
59 })
60
61 const columns = Effect.sync(() => stdout.columns ?? 0)
62 const rows = Effect.sync(() => stdout.rows ?? 0)
63
64 const readInput = Effect.gen(function*() {
65 yield* RcRef.get(rlRef)
66 const queue = yield* Queue.make<Terminal.UserInput, Cause.Done>()
67 const handleKeypress = (s: string | undefined, k: readline.Key) => {
68 const userInput = {
69 input: Option.fromUndefinedOr(s),
70 key: { name: k.name ?? "", ctrl: !!k.ctrl, meta: !!k.meta, shift: !!k.shift }
71 }
72 Queue.offerUnsafe(queue, userInput)
73 if (shouldQuit(userInput)) {
74 Queue.endUnsafe(queue)
75 }
76 }
77 yield* Effect.addFinalizer(() => Effect.sync(() => stdin.off("keypress", handleKeypress)))
78 stdin.on("keypress", handleKeypress)
79 return queue as Queue.Dequeue<Terminal.UserInput, Cause.Done>
80 })
81
82 const readLine = Effect.scoped(
83 Effect.flatMap(RcRef.get(rlRef), (readlineInterface) =>
84 Effect.callback<string, Terminal.QuitError>((resume) => {
85 const onLine = (line: string) => resume(Effect.succeed(line))
86 readlineInterface.once("line", onLine)
87 return Effect.sync(() => readlineInterface.off("line", onLine))
88 }))
89 )
90
91 const display = (prompt: string) =>
92 Effect.uninterruptible(
93 Effect.callback<void, PlatformError>((resume) => {
94 stdout.write(prompt, (err) =>
95 Predicate.isNullish(err)
96 ? resume(Effect.void)
97 : resume(Effect.fail(
98 badArgument({
99 module: "Terminal",
100 method: "display",
101 description: "Failed to write prompt to stdout",
102 cause: err
103 })
104 )))
105 })
106 )
107
108 return Terminal.make({
109 columns,
110 rows,
111 readInput,
112 readLine,
113 display
114 })
115 }
116)
117
118/**
119 * Provides the default process-backed `Terminal` service, ending key input on
120 * Ctrl+C or Ctrl+D.
121 *
122 * @category layers
123 * @since 4.0.0
124 */
125export const layer: Layer.Layer<Terminal.Terminal> = Layer.effect(Terminal.Terminal, make(defaultShouldQuit))
126
127function defaultShouldQuit(input: Terminal.UserInput) {
128 return input.key.ctrl && (input.key.name === "c" || input.key.name === "d")
129}