Skip to main content

nodejs/stdlib/
readline.rs

1//! Node `readline` module.
2//!
3//! * `'line'` and `'close'` events, and `for await (const line of rl)`: an
4//!   Interface listens to its input stream's `'data'`/`'end'` — from creation,
5//!   or for `process.stdin` from the first `'line'`/`'close'` listener or async
6//!   iterator, which sets standard input flowing (`process::stdin_call`). Lines split
7//!   on `\r\n`, `\n` or a lone `\r`, an unterminated last line is delivered at
8//!   end of input, then `'close'`. See "line events" below for the ordering.
9//! * `interface.question(query, cb)` writes `query` to stdout and, before any
10//!   line events have started, reads exactly ONE line from stdin synchronously
11//!   and invokes `cb(line)`; once they have, the answer is the next line the
12//!   input delivers. `readline/promises` resolves a promise instead.
13//! * `interface.write(data)` writes to the output; `prompt()` writes the stored
14//!   prompt; `setPrompt`/`getPrompt` manage it; the module cursor helpers
15//!   (`cursorTo`/`moveCursor`/`clearLine`/`clearScreenDown`) emit the
16//!   corresponding ANSI control sequences to stdout.
17//! * Not modelled: terminal mode (keypress decoding, history, line editing) —
18//!   input is read as lines whatever it is attached to — and `pause()`/
19//!   `resume()`, which return the Interface and change nothing.
20//!
21//! An Interface is a plain object tagged `@@native = "Interface"` carrying the
22//! passed `@@input`/`@@output` streams, the current `@@prompt`, a hidden
23//! `@@listeners` object of registered event callbacks, and the `@@rlid` that
24//! keys its line state.
25
26use crate::host::{is_callable, with_host, JsObj};
27use fusevm::Value;
28use indexmap::IndexMap;
29use std::collections::{HashMap, VecDeque};
30
31pub const METHODS: &[&str] = &[
32    "createInterface",
33    "clearLine",
34    "clearScreenDown",
35    "cursorTo",
36    "moveCursor",
37    "emitKeypressEvents",
38];
39
40/// Methods dispatched on an `@@native = "Interface"` object (reported to the
41/// parent for `instance_has_method` wiring).
42pub const INTERFACE_METHODS: &[&str] = &[
43    "question",
44    "write",
45    "close",
46    "pause",
47    "resume",
48    "prompt",
49    "setPrompt",
50    "getPrompt",
51    "on",
52    "once",
53    "addListener",
54    "prependListener",
55    "removeListener",
56    "off",
57    "removeAllListeners",
58    "@@asyncIterator",
59];
60
61/// The `readline/promises` surface: the same module, whose `createInterface`
62/// builds an Interface with a promise-returning `question`.
63pub const PROMISES_METHODS: &[&str] = &["createInterface"];
64
65pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
66    if method.starts_with("@@") {
67        return internal_call(method, args);
68    }
69    Some(match method {
70        "createInterface" => Ok(create_interface(args, false)),
71        // Cursor / line control: emit the ANSI sequence to stdout. Node passes the
72        // target stream as the first arg; node-js writes to the real stdout (the
73        // usual `process.stdout` target). Each returns `true` (write accepted).
74        "cursorTo" => {
75            let x = super::arg_num(args, 1);
76            let y = args.get(2).filter(|v| !matches!(v, Value::Undef));
77            let seq = match y {
78                Some(yv) => format!(
79                    "\x1b[{};{}H",
80                    with_host(|h| h.to_number(yv)) as i64 + 1,
81                    x as i64 + 1
82                ),
83                None => format!("\x1b[{}G", x as i64 + 1),
84            };
85            write_stdout(&seq);
86            Ok(Value::Bool(true))
87        }
88        "moveCursor" => {
89            let dx = super::arg_num(args, 1) as i64;
90            let dy = super::arg_num(args, 2) as i64;
91            let mut seq = String::new();
92            if dx > 0 {
93                seq.push_str(&format!("\x1b[{dx}C"));
94            } else if dx < 0 {
95                seq.push_str(&format!("\x1b[{}D", -dx));
96            }
97            if dy > 0 {
98                seq.push_str(&format!("\x1b[{dy}B"));
99            } else if dy < 0 {
100                seq.push_str(&format!("\x1b[{}A", -dy));
101            }
102            write_stdout(&seq);
103            Ok(Value::Bool(true))
104        }
105        "clearLine" => {
106            let dir = super::arg_num(args, 1);
107            // dir < 0 → to start (1K); dir > 0 → to end (0K); 0 → whole line (2K).
108            let seq = if dir < 0.0 {
109                "\x1b[1K"
110            } else if dir > 0.0 {
111                "\x1b[0K"
112            } else {
113                "\x1b[2K"
114            };
115            write_stdout(seq);
116            Ok(Value::Bool(true))
117        }
118        "clearScreenDown" => {
119            write_stdout("\x1b[0J");
120            Ok(Value::Bool(true))
121        }
122        // `readline.emitKeypressEvents(stream)` normally attaches an input decoder
123        // that makes `stream` emit `'keypress'` events. node-js has no background
124        // TTY reader driving async input events (see the module docs), so there is
125        // nothing to attach: an honest no-op rather than a fake key stream.
126        "emitKeypressEvents" => Ok(Value::Undef),
127        _ => return None,
128    })
129}
130
131/// `new readline.Interface(options | input[, output])` — the class form of
132/// `createInterface`, producing the same `@@native = "Interface"` object.
133/// Requires the parent to route `"Interface"` construction into this fn.
134pub fn construct(args: &[Value]) -> Result<Value, String> {
135    Ok(create_interface(args, false))
136}
137
138/// A non-function member of the `readline` namespace (reachable via
139/// `namespace_property` IF the parent routes `"readline"` into `stdlib::constant`).
140/// `readline.Interface` is the interface constructor.
141pub fn constant(name: &str) -> Option<Value> {
142    match name {
143        "Interface" => Some(with_host(|h| h.alloc(JsObj::Builtin("Interface".into())))),
144        _ => None,
145    }
146}
147
148/// `readline.createInterface(options | input[, output])` → an Interface object.
149/// `require('readline/promises').<method>`.
150pub fn promises_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
151    match method {
152        "createInterface" => Some(Ok(create_interface(args, true))),
153        _ => None,
154    }
155}
156
157fn create_interface(args: &[Value], promises: bool) -> Value {
158    let id = NEXT_ID.with(|n| {
159        let id = n.get();
160        n.set(id + 1);
161        id
162    });
163    // Options object form `{ input, output }` vs positional `(input, output)`.
164    let (input, output) = match args.first() {
165        Some(o) if opt_prop(o, "input").is_some() => (
166            opt_prop(o, "input").unwrap_or(Value::Undef),
167            opt_prop(o, "output").unwrap_or(Value::Undef),
168        ),
169        _ => (
170            args.first().cloned().unwrap_or(Value::Undef),
171            args.get(1).cloned().unwrap_or(Value::Undef),
172        ),
173    };
174    // `terminal`: the option, else whether the output is a TTY.
175    let terminal = match args.first().and_then(|o| opt_prop(o, "terminal")) {
176        Some(t) if !matches!(t, Value::Undef) => with_host(|h| h.truthy(&t)),
177        _ => {
178            matches!(output, Value::Obj(_))
179                && crate::builtins::get_property(&output, "isTTY")
180                    .map(|v| with_host(|h| h.truthy(&v)))
181                    .unwrap_or(false)
182        }
183    };
184    let iface = with_host(|h| {
185        let listeners = h.new_object(IndexMap::new());
186        let prompt = h.new_str("> ");
187        let mut m = IndexMap::new();
188        m.insert("@@native".into(), h.new_str("Interface"));
189        m.insert("@@input".into(), input.clone());
190        m.insert("@@output".into(), output.clone());
191        m.insert(
192            "@@terminal".into(),
193            h.new_str(if terminal { "1" } else { "0" }),
194        );
195        // node's own instance fields a caller reads.
196        m.insert("line".into(), h.new_str(""));
197        m.insert("output".into(), output);
198        m.insert("input".into(), input.clone());
199        m.insert("terminal".into(), Value::Bool(terminal));
200        m.insert("@@prompt".into(), prompt);
201        m.insert("@@listeners".into(), listeners);
202        m.insert("@@rlid".into(), Value::Float(id as f64));
203        if promises {
204            let flag = h.new_str("1");
205            m.insert("@@promises".into(), flag);
206        }
207        h.new_object(m)
208    });
209    if matches!(input, Value::Obj(_)) && !is_stdin(&input) {
210        attach_stream(&iface, &input);
211    }
212    iface
213}
214
215/// Dispatch a method on an Interface instance (`@@native = "Interface"`).
216pub fn instance_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
217    match method {
218        // REAL synchronous single-line read: write the query, read one stdin line,
219        // invoke the callback with it. Returns undefined (Node's callback form).
220        "question" => {
221            let query = with_host(|h| args.first().map(|v| h.str_of(v)).unwrap_or_default());
222            write_output(recv, &query);
223            // Once input is flowing as line events, the answer is the next
224            // line the stream delivers rather than a read of its own.
225            if with_state(recv, |s| s.flowing) {
226                if read_hidden(recv, "@@promises") == "1" {
227                    let (promise, id) = with_host(|h| {
228                        let p = h.new_promise();
229                        let id = h.promise_id(&p).unwrap_or(0);
230                        (p, id)
231                    });
232                    with_state(recv, |s| s.question = Some(QuestionReply::Promise(id)));
233                    return Ok(promise);
234                }
235                let cb = args
236                    .iter()
237                    .rev()
238                    .find(|v| with_host(|h| is_callable(h, v)))
239                    .cloned();
240                if let Some(cb) = cb {
241                    with_state(recv, |s| s.question = Some(QuestionReply::Callback(cb)));
242                }
243                return Ok(Value::Undef);
244            }
245            let line = read_line();
246            // `require('readline/promises')` builds an Interface whose
247            // `question` RESOLVES with the line instead of taking a callback.
248            // The two forms are the same read; only the handoff differs.
249            if read_hidden(recv, "@@promises") == "1" {
250                let line_val = with_host(|h| h.new_str(line));
251                return crate::builtins::promise_resolve_pub(line_val);
252            }
253            // The callback is the last callable argument (Node: `question(q, cb)`
254            // or `question(q, options, cb)`).
255            // The `.find` predicate receives `&&Value`; deref once so `is_callable`
256            // sees a `&Value`. `find` yields `Option<&Value>`, cloned to `Value`.
257            let cb = args
258                .iter()
259                .rev()
260                .find(|v| with_host(|h| is_callable(h, v)))
261                .cloned();
262            if let Some(cb) = cb {
263                let line_val = with_host(|h| h.new_str(line));
264                crate::host::invoke(&cb, vec![line_val], None)?;
265            }
266            Ok(Value::Undef)
267        }
268        // `rl.write(data)` on a non-terminal interface is input, as if the
269        // input stream had delivered it (node's `[kNormalWrite]`); a terminal
270        // one echoes it to the output.
271        "write" => {
272            let data = with_host(|h| args.first().map(|v| h.str_of(v)).unwrap_or_default());
273            if read_hidden(recv, "@@terminal") == "1" {
274                write_output(recv, &data);
275            } else {
276                on_data(recv, data.as_bytes())?;
277            }
278            Ok(Value::Undef)
279        }
280        "prompt" => {
281            let p = read_hidden(recv, "@@prompt");
282            write_output(recv, &p);
283            Ok(Value::Undef)
284        }
285        "setPrompt" => {
286            let p = with_host(|h| args.first().map(|v| h.str_of(v)).unwrap_or_default());
287            with_host(|h| {
288                let pv = h.new_str(p);
289                if let Some(JsObj::Object(m)) = h.get_mut(recv) {
290                    m.insert("@@prompt".into(), pv);
291                }
292            });
293            Ok(Value::Undef)
294        }
295        // `read_hidden` takes the host, so reading it INSIDE `with_host` borrowed
296        // the same RefCell twice and aborted the process — a Rust panic, not a
297        // throw, so no JS `try` could catch it. Read first, then borrow.
298        "getPrompt" => {
299            let prompt = read_hidden(recv, "@@prompt");
300            Ok(with_host(|h| h.new_str(prompt)))
301        }
302        // Listener registration, under `@@listeners[event]`. A `'line'` or
303        // `'close'` listener on standard input sets it flowing.
304        "on" | "once" | "addListener" | "prependListener" => {
305            if let (Some(ev), Some(cb)) = (args.first(), args.get(1)) {
306                let event = with_host(|h| h.str_of(ev));
307                store_listener(
308                    recv,
309                    &event,
310                    cb.clone(),
311                    method == "once",
312                    method == "prependListener",
313                );
314                if event == "line" || event == "close" {
315                    ensure_flowing(recv);
316                }
317            }
318            Ok(recv.clone())
319        }
320        "removeListener" | "off" => {
321            if let (Some(ev), Some(cb)) = (args.first(), args.get(1)) {
322                let event = with_host(|h| h.str_of(ev));
323                remove_listener(recv, &event, cb);
324            }
325            Ok(recv.clone())
326        }
327        "removeAllListeners" => {
328            let event = args
329                .first()
330                .filter(|v| !matches!(v, Value::Undef))
331                .map(|v| with_host(|h| h.str_of(v)));
332            clear_listeners(recv, event.as_deref());
333            Ok(recv.clone())
334        }
335        "close" => {
336            close(recv)?;
337            Ok(Value::Undef)
338        }
339        "@@asyncIterator" => Ok(async_iterator(recv)),
340        // Reading is driven by the input stream's own events; there is no
341        // separate flow switch to flip here.
342        "pause" | "resume" => Ok(recv.clone()),
343        _ => Err(crate::host::type_error(&format!(
344            "{method} is not a function"
345        ))),
346    }
347}
348
349/// Read the `key` hidden string property of `recv`.
350fn read_hidden(recv: &Value, key: &str) -> String {
351    with_host(|h| match h.get(recv) {
352        Some(JsObj::Object(p)) => p.get(key).map(|v| h.str_of(v)).unwrap_or_default(),
353        _ => String::new(),
354    })
355}
356
357/// The `@@listeners` object of `recv`.
358fn listeners_obj(recv: &Value) -> Option<Value> {
359    opt_prop(recv, "@@listeners")
360}
361
362/// Add `cb` to `recv`'s `@@listeners[event]`, an array of `[callback, once]`
363/// pairs (created on demand); `prepend` puts it first.
364fn store_listener(recv: &Value, event: &str, cb: Value, once: bool, prepend: bool) {
365    let Some(listeners) = listeners_obj(recv) else {
366        return;
367    };
368    with_host(|h| {
369        let entry = h.new_array(vec![cb, Value::Bool(once)]);
370        let arr = match h.get(&listeners) {
371            Some(JsObj::Object(p)) => p.get(event).cloned(),
372            _ => None,
373        };
374        let arr = arr.filter(|a| matches!(h.get(a), Some(JsObj::Array(_))));
375        match arr {
376            Some(a) => {
377                if let Some(JsObj::Array(items)) = h.get_mut(&a) {
378                    if prepend {
379                        items.insert(0, entry);
380                    } else {
381                        items.push(entry);
382                    }
383                }
384            }
385            None => {
386                let a = h.new_array(vec![entry]);
387                if let Some(JsObj::Object(p)) = h.get_mut(&listeners) {
388                    p.insert(event.to_string(), a);
389                }
390            }
391        }
392    });
393}
394
395/// The `(callback, once)` pairs registered for `event`, in call order.
396fn listener_entries(recv: &Value, event: &str) -> Vec<(Value, bool)> {
397    let Some(listeners) = listeners_obj(recv) else {
398        return Vec::new();
399    };
400    with_host(|h| {
401        let arr = match h.get(&listeners) {
402            Some(JsObj::Object(p)) => p.get(event).cloned(),
403            _ => None,
404        };
405        let Some(Some(JsObj::Array(items))) = arr.map(|a| h.get(&a).cloned()) else {
406            return Vec::new();
407        };
408        items
409            .iter()
410            .filter_map(|e| match h.get(e) {
411                Some(JsObj::Array(pair)) if pair.len() == 2 => {
412                    Some((pair[0].clone(), h.truthy(&pair[1])))
413                }
414                _ => None,
415            })
416            .collect()
417    })
418}
419
420/// Remove the first registration of `cb` for `event`.
421fn remove_listener(recv: &Value, event: &str, cb: &Value) {
422    let Some(listeners) = listeners_obj(recv) else {
423        return;
424    };
425    with_host(|h| {
426        let arr = match h.get(&listeners) {
427            Some(JsObj::Object(p)) => p.get(event).cloned(),
428            _ => None,
429        };
430        let Some(arr) = arr else { return };
431        let pos = match h.get(&arr) {
432            Some(JsObj::Array(items)) => items.iter().position(|e| match h.get(e) {
433                Some(JsObj::Array(pair)) => pair.first().is_some_and(|f| h.strict_eq(f, cb)),
434                _ => false,
435            }),
436            _ => None,
437        };
438        if let (Some(i), Some(JsObj::Array(items))) = (pos, h.get_mut(&arr)) {
439            items.remove(i);
440        }
441    });
442}
443
444/// `removeAllListeners([event])`.
445fn clear_listeners(recv: &Value, event: Option<&str>) {
446    let Some(listeners) = listeners_obj(recv) else {
447        return;
448    };
449    with_host(|h| {
450        if let Some(JsObj::Object(p)) = h.get_mut(&listeners) {
451            match event {
452                Some(e) => {
453                    p.shift_remove(e);
454                }
455                None => p.clear(),
456            }
457        }
458    });
459}
460
461/// Read one line from stdin, stripping the trailing CR/LF. EOF yields "".
462fn read_line() -> String {
463    let mut line = String::new();
464    let _ = crate::host::with_stdin_reader(|r| r.read_line(&mut line));
465    while line.ends_with('\n') || line.ends_with('\r') {
466        line.pop();
467    }
468    line
469}
470
471/// Write `s` as program stdout (a cursor-control sequence) through the host's
472/// output sink, so an embedder's capture sees it like any `console.log`.
473fn write_stdout(s: &str) {
474    with_host(|h| h.write_out(s, false));
475}
476
477/// Write to the interface's configured `output` stream, falling back to stdout
478/// when it has none.
479///
480/// `createInterface({input, output})` records `@@output` and Node writes
481/// `prompt()` and `write()` THROUGH it — the option exists so a caller can
482/// capture or redirect that text. Both went straight to `io::stdout()` here, so
483/// an interface given its own output printed to the process's stdout anyway and
484/// the supplied stream never saw a byte.
485///
486/// With no `output` node writes nothing at all (`_writeToOutput` tests
487/// `this.output !== null && this.output !== undefined`); this fell back to the
488/// process's stdout.
489fn write_output(recv: &Value, s: &str) {
490    let out = opt_prop(recv, "@@output").unwrap_or(Value::Undef);
491    if matches!(out, Value::Obj(_)) && !with_host(|h| h.is_null(&out)) {
492        let payload = with_host(|h| h.new_str(s.to_string()));
493        let _ = crate::host::call_method(&out, "write", vec![payload]);
494    }
495}
496
497/// An own property of `v` if `v` is a plain object, else `None`.
498fn opt_prop(v: &Value, key: &str) -> Option<Value> {
499    with_host(|h| match h.get(v) {
500        Some(JsObj::Object(p)) => p.get(key).cloned(),
501        _ => None,
502    })
503}
504
505// ── line events ──────────────────────────────────────────────────────────────
506//
507// An Interface splits its input into lines and emits `'line'` for each, then
508// `'close'` when the input ends, as node's does. It listens to its input
509// stream's `'data'`/`'end'` (standard input reads through the same Rust buffer
510// `question` reads, so the two never skip each other's bytes). A chunk's lines
511// are emitted synchronously, one after another, as node emits them.
512
513/// Per-Interface line state, keyed by the Interface's `@@rlid`.
514#[derive(Default)]
515struct LineState {
516    /// Bytes received but not yet ended by a line break.
517    pending: Vec<u8>,
518    /// The last chunk ended in `\r`, so a `\n` opening the next one is part of
519    /// that line break rather than an empty line.
520    after_cr: bool,
521    /// Complete lines not yet emitted.
522    to_emit: VecDeque<String>,
523    /// A chain of line emissions is in progress.
524    emitting: bool,
525    /// The input has ended: `'close'` follows the last line.
526    ended: bool,
527    closed: bool,
528    /// The input is flowing into this Interface (always, for a stream input;
529    /// from the first listener, for standard input).
530    flowing: bool,
531    /// Async iteration: lines no `next()` has taken yet, and the promises of
532    /// the `next()` calls waiting for one.
533    iterating: bool,
534    buffered: VecDeque<String>,
535    waiters: VecDeque<u32>,
536    /// A `question` waiting for the next line: its callback, or (for
537    /// `readline/promises`) the id of the promise it returned.
538    question: Option<QuestionReply>,
539}
540
541enum QuestionReply {
542    Callback(Value),
543    Promise(u32),
544}
545
546thread_local! {
547    static LINES: std::cell::RefCell<HashMap<u64, LineState>> =
548        std::cell::RefCell::new(HashMap::new());
549    static NEXT_ID: std::cell::Cell<u64> = const { std::cell::Cell::new(1) };
550}
551
552fn rl_id(recv: &Value) -> u64 {
553    opt_prop(recv, "@@rlid")
554        .map(|v| with_host(|h| h.to_number(&v)) as u64)
555        .unwrap_or(0)
556}
557
558fn with_state<R>(recv: &Value, f: impl FnOnce(&mut LineState) -> R) -> R {
559    let id = rl_id(recv);
560    LINES.with(|m| f(m.borrow_mut().entry(id).or_default()))
561}
562
563/// Whether `input` is `process.stdin`.
564fn is_stdin(input: &Value) -> bool {
565    with_host(|h| match h.get(input) {
566        Some(JsObj::Object(p)) => {
567            p.get("@@native").map(|v| h.str_of(v)).as_deref() == Some("WriteStream")
568                && p.get("fd").map(|v| h.to_number(v)) == Some(0.0)
569        }
570        _ => false,
571    })
572}
573
574/// Start reading standard input, once, if that is this Interface's input.
575fn ensure_flowing(recv: &Value) {
576    let input = opt_prop(recv, "@@input").unwrap_or(Value::Undef);
577    if !is_stdin(&input) {
578        return;
579    }
580    let start = with_state(recv, |s| {
581        !std::mem::replace(&mut s.flowing, true) && !s.closed
582    });
583    if start {
584        attach_stream(recv, &input);
585    }
586}
587
588/// Split a chunk into lines on `\r\n`, `\n` or a lone `\r`, keeping the
589/// unterminated tail for the next chunk.
590fn on_data(recv: &Value, bytes: &[u8]) -> Result<(), String> {
591    // A closed Interface has stopped listening to its input.
592    if with_state(recv, |s| s.closed) {
593        return Ok(());
594    }
595    let start = with_state(recv, |s| {
596        let mut i = 0;
597        if s.after_cr && bytes.first() == Some(&b'\n') {
598            i = 1;
599        }
600        s.after_cr = false;
601        while i < bytes.len() {
602            match bytes[i] {
603                b'\n' => {
604                    let line = String::from_utf8_lossy(&s.pending).into_owned();
605                    s.pending.clear();
606                    s.to_emit.push_back(line);
607                }
608                b'\r' => {
609                    let line = String::from_utf8_lossy(&s.pending).into_owned();
610                    s.pending.clear();
611                    s.to_emit.push_back(line);
612                    match bytes.get(i + 1) {
613                        Some(b'\n') => i += 1,
614                        None => s.after_cr = true,
615                        _ => {}
616                    }
617                }
618                b => s.pending.push(b),
619            }
620            i += 1;
621        }
622        !s.to_emit.is_empty() && !std::mem::replace(&mut s.emitting, true)
623    });
624    if start {
625        emit_lines(recv)?;
626    }
627    Ok(())
628}
629
630/// The input ended: what is left unterminated is the last line, then `'close'`.
631fn on_end(recv: &Value) -> Result<(), String> {
632    let (start, close_now) = with_state(recv, |s| {
633        s.ended = true;
634        if !s.pending.is_empty() {
635            let line = String::from_utf8_lossy(&s.pending).into_owned();
636            s.pending.clear();
637            s.to_emit.push_back(line);
638        }
639        let start = !s.to_emit.is_empty() && !std::mem::replace(&mut s.emitting, true);
640        (start, s.to_emit.is_empty() && !s.emitting)
641    });
642    if start {
643        emit_lines(recv)?;
644    } else if close_now {
645        close(recv)?;
646    }
647    Ok(())
648}
649
650/// Emit every queued line, in order and synchronously — node emits a chunk's
651/// lines in one go, so the microtasks a `'line'` listener queues run after the
652/// whole chunk — then `'close'` if the input has ended. A line arriving while
653/// this runs (a listener feeding the input) joins the same loop.
654fn emit_lines(recv: &Value) -> Result<(), String> {
655    while let Some(line) = with_state(recv, |s| s.to_emit.pop_front()) {
656        if let Err(e) = deliver(recv, line) {
657            with_state(recv, |s| s.emitting = false);
658            return Err(e);
659        }
660    }
661    let close_now = with_state(recv, |s| {
662        s.emitting = false;
663        s.ended
664    });
665    if close_now {
666        close(recv)?;
667    }
668    Ok(())
669}
670
671/// Hand one line to a waiting `question`, or else to the `'line'` listeners
672/// and any async iterator.
673fn deliver(recv: &Value, line: String) -> Result<(), String> {
674    match with_state(recv, |s| s.question.take()) {
675        Some(QuestionReply::Callback(cb)) => {
676            let v = with_host(|h| h.new_str(line));
677            crate::host::invoke(&cb, vec![v], None)?;
678            return Ok(());
679        }
680        Some(QuestionReply::Promise(id)) => {
681            let v = with_host(|h| h.new_str(line));
682            crate::host::resolve_promise_val(id, v);
683            return Ok(());
684        }
685        None => {}
686    }
687    let v = with_host(|h| h.new_str(line.clone()));
688    emit(recv, "line", vec![v.clone()])?;
689    let waiter = with_state(recv, |s| {
690        if !s.iterating {
691            return None;
692        }
693        let w = s.waiters.pop_front();
694        if w.is_none() {
695            s.buffered.push_back(line);
696        }
697        w
698    });
699    if let Some(id) = waiter {
700        crate::host::resolve_promise_val(id, iter_result(v, false));
701    }
702    Ok(())
703}
704
705/// `rl.close()`, and the end of input: emit `'close'` once and finish any
706/// async iteration.
707fn close(recv: &Value) -> Result<(), String> {
708    let waiters = with_state(recv, |s| {
709        if std::mem::replace(&mut s.closed, true) {
710            return None;
711        }
712        Some(std::mem::take(&mut s.waiters))
713    });
714    let Some(waiters) = waiters else {
715        return Ok(());
716    };
717    // node sets `closed` on the instance when it closes.
718    with_host(|h| {
719        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
720            p.insert("closed".into(), Value::Bool(true));
721        }
722    });
723    // A closed Interface stops its input, so standard input no longer holds
724    // the process open.
725    let input = opt_prop(recv, "@@input").unwrap_or(Value::Undef);
726    if is_stdin(&input) {
727        crate::host::call_method(&input, "pause", Vec::new())?;
728    }
729    emit(recv, "close", Vec::new())?;
730    for id in waiters {
731        crate::host::resolve_promise_val(id, iter_result(Value::Undef, true));
732    }
733    Ok(())
734}
735
736/// Call the listeners registered for `event`, `once` ones removed first.
737fn emit(recv: &Value, event: &str, args: Vec<Value>) -> Result<(), String> {
738    let entries = listener_entries(recv, event);
739    for (cb, once) in entries {
740        if once {
741            remove_listener(recv, event, &cb);
742        }
743        crate::host::invoke(&cb, args.clone(), Some(recv.clone()))?;
744    }
745    Ok(())
746}
747
748/// `{ value, done }`.
749fn iter_result(value: Value, done: bool) -> Value {
750    with_host(|h| {
751        let mut m = IndexMap::new();
752        m.insert("value".into(), value);
753        m.insert("done".into(), Value::Bool(done));
754        h.new_object(m)
755    })
756}
757
758/// Module-internal entry points reached through `readline.@@…` builtins: the
759/// listeners attached to the input stream, and the deferred `close`.
760fn internal_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
761    let recv = args.first().cloned().unwrap_or(Value::Undef);
762    let r = match method {
763        "@@feed" => {
764            let chunk = args.get(1).cloned().unwrap_or(Value::Undef);
765            let bytes = super::buffer::view_bytes(&chunk)
766                .unwrap_or_else(|| with_host(|h| h.str_of(&chunk)).into_bytes());
767            on_data(&recv, &bytes)
768        }
769        "@@end" => on_end(&recv),
770        "@@close" => close(&recv),
771        _ => return None,
772    };
773    Some(r.map(|_| Value::Undef))
774}
775
776/// Listen to a stream input's `'data'` and `'end'`, as node's Interface does
777/// from the moment it is created.
778fn attach_stream(recv: &Value, input: &Value) {
779    with_state(recv, |s| s.flowing = true);
780    let has_on = crate::builtins::get_property(input, "on")
781        .map(|f| with_host(|h| is_callable(h, &f)))
782        .unwrap_or(false);
783    if !has_on {
784        return;
785    }
786    for (event, internal) in [("data", "readline.@@feed"), ("end", "readline.@@end")] {
787        let (name, cb) = with_host(|h| {
788            let target = h.alloc(JsObj::Builtin(internal.into()));
789            let undef = Value::Undef;
790            let cb = h.alloc(JsObj::BoundFunc {
791                target,
792                this: undef,
793                args: vec![recv.clone()],
794            });
795            (h.new_str(event), cb)
796        });
797        let _ = crate::host::call_method(input, "on", vec![name, cb]);
798    }
799}
800
801/// The async iterator `for await (const line of rl)` reads: it takes the lines
802/// emitted from the moment it is created, and ends at `'close'`. Leaving the
803/// loop early (`return()`) closes the Interface, as in node.
804pub const ITERATOR_METHODS: &[&str] = &["next", "return", "@@asyncIterator"];
805
806fn async_iterator(recv: &Value) -> Value {
807    with_state(recv, |s| s.iterating = true);
808    ensure_flowing(recv);
809    with_host(|h| {
810        let mut m = IndexMap::new();
811        m.insert("@@native".into(), h.new_str("ReadlineIterator"));
812        m.insert("@@iface".into(), recv.clone());
813        h.new_object(m)
814    })
815}
816
817pub fn iterator_call(recv: &Value, method: &str) -> Result<Value, String> {
818    let iface = opt_prop(recv, "@@iface").unwrap_or(Value::Undef);
819    match method {
820        "@@asyncIterator" => Ok(recv.clone()),
821        "next" => {
822            let ready = with_state(&iface, |s| match s.buffered.pop_front() {
823                Some(line) => Some(Some(line)),
824                None if s.closed => Some(None),
825                None => None,
826            });
827            match ready {
828                Some(Some(line)) => {
829                    let v = with_host(|h| h.new_str(line));
830                    crate::builtins::promise_resolve_pub(iter_result(v, false))
831                }
832                Some(None) => crate::builtins::promise_resolve_pub(iter_result(Value::Undef, true)),
833                None => {
834                    let (promise, id) = with_host(|h| {
835                        let p = h.new_promise();
836                        let id = h.promise_id(&p).unwrap_or(0);
837                        (p, id)
838                    });
839                    with_state(&iface, |s| s.waiters.push_back(id));
840                    Ok(promise)
841                }
842            }
843        }
844        // Leaving the loop closes the Interface on the next tick, so the code
845        // after the loop runs before `'close'` fires, as in node.
846        "return" => {
847            with_host(|h| {
848                let cb = h.alloc(JsObj::Builtin("readline.@@close".into()));
849                h.queue_nexttick(cb, vec![iface.clone()]);
850            });
851            crate::builtins::promise_resolve_pub(iter_result(Value::Undef, true))
852        }
853        _ => Err(crate::host::type_error(&format!(
854            "{method} is not a function"
855        ))),
856    }
857}