1use crate::host::{with_host, JsObj};
10use fusevm::Value;
11use indexmap::IndexMap;
12use std::cell::{Cell, RefCell};
13use std::collections::HashMap;
14use std::io::IsTerminal;
15use std::time::Instant;
16
17pub const METHODS: &[&str] = &[
18 "log",
19 "info",
20 "debug",
21 "error",
22 "warn",
23 "dir",
24 "dirxml",
25 "trace",
26 "assert",
27 "count",
28 "countReset",
29 "group",
30 "groupCollapsed",
31 "groupEnd",
32 "time",
33 "timeEnd",
34 "timeLog",
35 "table",
36 "clear",
37 "timeStamp",
38 "profile",
39 "profileEnd",
40];
41
42pub const CONSOLE_METHODS: &[&str] = METHODS;
45
46thread_local! {
47 static GROUP_DEPTH: Cell<usize> = const { Cell::new(0) };
49 static COUNTS: RefCell<HashMap<String, u64>> = RefCell::new(HashMap::new());
51 static TIMERS: RefCell<HashMap<String, Instant>> = RefCell::new(HashMap::new());
53 static SINK: RefCell<Option<(Value, Value)>> = const { RefCell::new(None) };
57}
58
59pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
60 Some(match method {
61 "log" | "info" | "debug" | "dirxml" => {
62 match format_args(args) {
65 Ok(s) => {
66 emit(&s, false);
67 Ok(Value::Undef)
68 }
69 Err(e) => Err(e),
70 }
71 }
72 "error" | "warn" => match format_args(args) {
73 Ok(s) => {
74 emit(&s, true);
75 Ok(Value::Undef)
76 }
77 Err(e) => Err(e),
78 },
79 "dir" => {
85 let opts = dir_options(args.get(1));
86 let target = args.first().cloned().unwrap_or(Value::Undef);
87 match crate::stdlib::util::call("inspect", &[target, opts]) {
88 Some(Ok(s)) => {
89 emit(&with_host(|h| h.str_of(&s)), false);
90 Ok(Value::Undef)
91 }
92 Some(Err(e)) => Err(e),
93 None => Ok(Value::Undef),
94 }
95 }
96 "trace" => {
100 let msg = match format_args(args) {
101 Ok(s) => s,
102 Err(e) => return Some(Err(e)),
103 };
104 let line = if msg.is_empty() {
105 "Trace".to_string()
106 } else {
107 format!("Trace: {msg}")
108 };
109 emit(&line, true);
110 Ok(Value::Undef)
111 }
112 "assert" => {
115 let ok = with_host(|h| h.truthy(&args.first().cloned().unwrap_or(Value::Undef)));
116 if !ok {
117 let msg = match format_args(&args[1.min(args.len())..]) {
118 Ok(s) => s,
119 Err(e) => return Some(Err(e)),
120 };
121 let line = if msg.is_empty() {
122 "Assertion failed".to_string()
123 } else {
124 format!("Assertion failed: {msg}")
125 };
126 emit(&line, true);
127 }
128 Ok(Value::Undef)
129 }
130 "count" => {
131 let label = label_arg(args, "default");
132 let n = COUNTS.with(|c| {
133 let mut m = c.borrow_mut();
134 let e = m.entry(label.clone()).or_insert(0);
135 *e += 1;
136 *e
137 });
138 emit(&format!("{label}: {n}"), false);
139 Ok(Value::Undef)
140 }
141 "countReset" => {
142 let label = label_arg(args, "default");
143 COUNTS.with(|c| c.borrow_mut().remove(&label));
144 Ok(Value::Undef)
145 }
146 "group" | "groupCollapsed" => {
149 if !args.is_empty() {
150 match format_args(args) {
151 Ok(s) => emit(&s, false),
152 Err(e) => return Some(Err(e)),
153 }
154 }
155 GROUP_DEPTH.with(|d| d.set(d.get() + 1));
156 Ok(Value::Undef)
157 }
158 "groupEnd" => {
159 GROUP_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
160 Ok(Value::Undef)
161 }
162 "time" => {
163 let label = label_arg(args, "default");
164 TIMERS.with(|t| t.borrow_mut().insert(label, Instant::now()));
165 Ok(Value::Undef)
166 }
167 "timeEnd" | "timeLog" => {
168 let label = label_arg(args, "default");
169 let elapsed = TIMERS.with(|t| {
170 let m = t.borrow();
171 m.get(&label).map(|start| start.elapsed())
172 });
173 match elapsed {
174 Some(d) => {
175 let ms = d.as_secs_f64() * 1000.0;
176 let extra = if args.len() > 1 {
178 match format_args(&args[1..]) {
179 Ok(s) => format!(" {s}"),
180 Err(e) => return Some(Err(e)),
181 }
182 } else {
183 String::new()
184 };
185 emit(&format!("{label}: {ms:.3}ms{extra}"), false);
186 if method == "timeEnd" {
187 TIMERS.with(|t| t.borrow_mut().remove(&label));
188 }
189 }
190 None => emit(
191 &format!("Warning: No such label '{label}' for console.{method}()"),
192 true,
193 ),
194 }
195 Ok(Value::Undef)
196 }
197 "table" => {
200 match render_table(args) {
201 Err(e) => return Some(Err(e)),
202 Ok(Some(t)) => emit(&t, false),
203 Ok(None) => match format_args(&args[..args.len().min(1)]) {
205 Ok(s) => emit(&s, false),
206 Err(e) => return Some(Err(e)),
207 },
208 }
209 Ok(Value::Undef)
210 }
211 "clear" => {
214 let is_tty = SINK.with(|s| s.borrow().is_some()) || std::io::stdout().is_terminal();
215 if is_tty {
216 emit("\u{1b}[2J\u{1b}[0f", false);
217 }
218 Ok(Value::Undef)
219 }
220 "timeStamp" | "profile" | "profileEnd" => Ok(Value::Undef),
223 _ => return None,
224 })
225}
226
227pub fn construct(args: &[Value]) -> Result<Value, String> {
231 let first = args.first().cloned().unwrap_or(Value::Undef);
232 let is_options = with_host(|h| match h.get(&first) {
234 Some(JsObj::Object(m)) => m.contains_key("stdout"),
235 _ => false,
236 });
237 let (stdout, stderr) = if is_options {
238 let out = crate::builtins::get_property(&first, "stdout").unwrap_or(Value::Undef);
239 let err = match crate::builtins::get_property(&first, "stderr") {
240 Ok(Value::Undef) | Err(_) => out.clone(),
241 Ok(v) => v,
242 };
243 (out, err)
244 } else {
245 let err = args
246 .get(1)
247 .cloned()
248 .filter(|v| !matches!(v, Value::Undef))
249 .unwrap_or_else(|| first.clone());
250 (first, err)
251 };
252 Ok(with_host(|h| {
253 let mut m = IndexMap::new();
254 m.insert("@@native".into(), h.new_str("Console"));
255 m.insert("@@stdout".into(), stdout);
256 m.insert("@@stderr".into(), stderr);
257 h.new_object(m)
258 }))
259}
260
261pub fn instance_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
265 let streams = with_host(|h| match h.get(recv) {
266 Some(JsObj::Object(m)) => Some((
267 m.get("@@stdout").cloned().unwrap_or(Value::Undef),
268 m.get("@@stderr").cloned().unwrap_or(Value::Undef),
269 )),
270 _ => None,
271 });
272 let prev = SINK.with(|s| s.borrow_mut().take());
273 SINK.with(|s| *s.borrow_mut() = streams);
274 let r = call(method, &args).unwrap_or(Ok(Value::Undef));
275 SINK.with(|s| *s.borrow_mut() = prev);
276 r
277}
278
279fn format_args(args: &[Value]) -> Result<String, String> {
282 super::util::format(args)
285}
286
287fn dir_options(options: Option<&Value>) -> Value {
291 let mut props: IndexMap<String, Value> = IndexMap::new();
292 props.insert("customInspect".into(), Value::Bool(false));
293 if let Some(o) = options.filter(|o| matches!(o, Value::Obj(_))) {
294 for (k, v) in crate::host::own_enum_entries_deep(o).unwrap_or_default() {
296 props.insert(k, v);
297 }
298 }
299 with_host(|h| h.new_object(props))
300}
301
302fn label_arg(args: &[Value], fallback: &str) -> String {
303 match args.first() {
304 Some(v) => with_host(|h| h.str_of(v)),
305 None => fallback.to_string(),
306 }
307}
308
309fn emit(line: &str, stderr: bool) {
313 let depth = GROUP_DEPTH.with(|d| d.get());
314 let out = if depth == 0 {
315 line.to_string()
316 } else {
317 let pad = " ".repeat(depth);
318 format!("{pad}{}", line.replace('\n', &format!("\n{pad}")))
319 };
320 let stream = SINK.with(|s| {
322 s.borrow().as_ref().and_then(|(o, e)| {
323 let target = if stderr { e } else { o };
324 matches!(target, Value::Obj(_)).then(|| target.clone())
325 })
326 });
327 if let Some(stream) = stream {
328 let payload = with_host(|h| h.new_str(format!("{out}\n")));
329 if crate::host::call_method(&stream, "write", vec![payload]).is_ok() {
330 return;
331 }
332 }
333 with_host(|h| h.write_out(&format!("{out}\n"), stderr));
334}
335
336type TableEntries = Vec<(Value, Value)>;
343
344fn render_table(args: &[Value]) -> Result<Option<String>, String> {
347 let data = args.first().cloned().unwrap_or(Value::Undef);
348 let properties = args.get(1).cloned().unwrap_or(Value::Undef);
349 let properties: Option<Vec<Value>> = match with_host(|h| h.get(&properties).cloned()) {
350 _ if matches!(properties, Value::Undef) => None,
351 Some(JsObj::Array(items)) => Some(items),
352 _ => {
353 return Err(crate::host::coded_error(
354 "TypeError",
355 "ERR_INVALID_ARG_TYPE",
356 &format!(
357 "The \"properties\" argument must be an instance of Array. Received {}",
358 crate::stdlib::received_desc(&properties)
359 ),
360 ))
361 }
362 };
363 if with_host(|h| crate::host::is_primitive(h, &data) || h.is_null(&data)) {
364 return Ok(None);
365 }
366 let index_array = |n: usize| -> Result<Vec<Option<String>>, String> {
367 (0..n)
368 .map(|i| table_inspect(&Value::Float(i as f64)).map(Some))
369 .collect()
370 };
371
372 let view = with_host(|h| crate::builtins::collection_iterator_view(h, &data));
375 let (map_entries, set_values): (Option<TableEntries>, Option<Vec<Value>>) =
376 match (view, with_host(|h| h.get(&data).cloned())) {
377 (Some(("Map Entries", rest)), _) => (Some(rest), None),
378 (Some(("Set Entries", rest)), _) => (
381 None,
382 Some(rest.into_iter().flat_map(|(k, v)| [k, v]).collect()),
383 ),
384 (Some((_, rest)), _) => (None, Some(rest.into_iter().map(|(k, _)| k).collect())),
385 (None, Some(JsObj::Map { entries, .. })) => {
386 (Some(entries.values().cloned().collect()), None)
387 }
388 (None, Some(JsObj::Set { entries, .. })) => {
389 (None, Some(entries.values().cloned().collect()))
390 }
391 _ => (None, None),
392 };
393 if let Some(pairs) = map_entries {
394 let mut keys = Vec::with_capacity(pairs.len());
395 let mut values = Vec::with_capacity(pairs.len());
396 for (k, v) in &pairs {
397 keys.push(Some(table_inspect(k)?));
398 values.push(Some(table_inspect(v)?));
399 }
400 let head = ["(iteration index)", "Key", "Values"].map(str::to_string);
401 return Ok(Some(cli_table(
402 &head,
403 &[index_array(pairs.len())?, keys, values],
404 )));
405 }
406 if let Some(items) = set_values {
407 let values = items
408 .iter()
409 .map(|v| table_inspect(v).map(Some))
410 .collect::<Result<Vec<_>, _>>()?;
411 let head = ["(iteration index)", "Values"].map(str::to_string);
412 return Ok(Some(cli_table(&head, &[index_array(items.len())?, values])));
413 }
414
415 let index_keys = object_keys(&data)?;
418 let mut map: Vec<(String, Vec<Option<String>>)> = Vec::new();
419 let mut has_primitives = false;
420 let mut values_column: Vec<Option<String>> = Vec::new();
421 for (i, k) in index_keys.iter().enumerate() {
422 let item = crate::builtins::get_property(&data, k)?;
423 let primitive = with_host(|h| h.is_nullish(&item) || crate::host::is_primitive(h, &item));
424 if properties.is_none() && primitive {
425 has_primitives = true;
426 set_cell(&mut values_column, i, table_inspect(&item)?);
427 continue;
428 }
429 let keys: Vec<String> = match &properties {
430 Some(p) => p
431 .iter()
432 .map(crate::host::to_property_key)
433 .collect::<Result<_, _>>()?,
434 None => object_keys(&item)?,
435 };
436 for key in keys {
437 let pos = match map.iter().position(|(k, _)| *k == key) {
438 Some(p) => p,
439 None => {
440 map.push((key.clone(), Vec::new()));
441 map.len() - 1
442 }
443 };
444 let cell = if (primitive && properties.is_some()) || !has_own(&item, &key)? {
445 String::new()
446 } else {
447 table_inspect(&crate::builtins::get_property(&item, &key)?)?
448 };
449 set_cell(&mut map[pos].1, i, cell);
450 }
451 }
452 let (mut ordered, rest): (Vec<_>, Vec<_>) = map
454 .into_iter()
455 .partition(|(k, _)| crate::host::array_index(k).is_some());
456 ordered.sort_by_key(|(k, _)| crate::host::array_index(k));
457 ordered.extend(rest);
458 let mut head = vec!["(index)".to_string()];
459 let mut columns = vec![index_keys.into_iter().map(Some).collect::<Vec<_>>()];
460 for (k, col) in ordered {
461 head.push(k);
462 columns.push(col);
463 }
464 if has_primitives {
465 head.push("Values".to_string());
466 columns.push(values_column);
467 }
468 Ok(Some(cli_table(&head, &columns)))
469}
470
471fn set_cell(column: &mut Vec<Option<String>>, i: usize, cell: String) {
473 if column.len() <= i {
474 column.resize(i + 1, None);
475 }
476 column[i] = Some(cell);
477}
478
479fn object_keys(v: &Value) -> Result<Vec<String>, String> {
481 let keys = crate::builtins::call_builtin_function("Object.keys", vec![v.clone()])?;
482 Ok(with_host(|h| match h.get(&keys) {
483 Some(JsObj::Array(items)) => items.iter().map(|k| h.str_of(k)).collect(),
484 _ => Vec::new(),
485 }))
486}
487
488fn has_own(v: &Value, key: &str) -> Result<bool, String> {
489 let k = with_host(|h| h.new_str(key.to_string()));
490 let r = crate::builtins::object_builtin_method(v, "hasOwnProperty", vec![k])?;
491 Ok(with_host(|h| h.truthy(&r)))
492}
493
494fn table_inspect(v: &Value) -> Result<String, String> {
498 let view = matches!(
500 crate::stdlib::native_tag(v).as_deref(),
501 Some("TypedArray" | "Buffer")
502 );
503 let collapse = !view
504 && with_host(|h| {
505 !crate::host::is_primitive(h, v)
506 && !h.is_nullish(v)
507 && !matches!(h.get(v), Some(JsObj::Array(_)))
508 })
509 && object_keys(v)?.len() > 2;
510 let opts = with_host(|h| {
511 let mut m: IndexMap<String, Value> = IndexMap::new();
512 m.insert(
513 "depth".into(),
514 Value::Float(if collapse { -1.0 } else { 0.0 }),
515 );
516 m.insert("maxArrayLength".into(), Value::Float(3.0));
517 m.insert("breakLength".into(), Value::Float(f64::INFINITY));
518 h.new_object(m)
519 });
520 let out = crate::stdlib::util::call("inspect", &[v.clone(), opts])
521 .unwrap_or_else(|| Ok(with_host(|h| h.new_str(h.inspect(v)))))?;
522 Ok(with_host(|h| h.str_of(&out)))
523}
524
525fn string_width(s: &str) -> usize {
530 use unicode_normalization::UnicodeNormalization;
531 let s: String = crate::stdlib::util::strip_vt(s).nfc().collect();
532 s.chars()
533 .map(|c| {
534 let code = c as u32;
535 if is_full_width(code) {
536 2
537 } else if is_zero_width(code) {
538 0
539 } else {
540 1
541 }
542 })
543 .sum()
544}
545
546fn is_zero_width(code: u32) -> bool {
547 code <= 0x1F
548 || (0x7F..=0x9F).contains(&code)
549 || (0x300..=0x36F).contains(&code)
550 || (0x200B..=0x200F).contains(&code)
551 || (0x20D0..=0x20FF).contains(&code)
552 || (0xFE00..=0xFE0F).contains(&code)
553 || (0xFE20..=0xFE2F).contains(&code)
554 || (0xE0100..=0xE01EF).contains(&code)
555}
556
557fn is_full_width(code: u32) -> bool {
558 code >= 0x1100
559 && (code <= 0x115f
560 || code == 0x2329
561 || code == 0x232a
562 || ((0x2e80..=0x3247).contains(&code) && code != 0x303f)
563 || (0x3250..=0x4dbf).contains(&code)
564 || (0x4e00..=0xa4c6).contains(&code)
565 || (0xa960..=0xa97c).contains(&code)
566 || (0xac00..=0xd7a3).contains(&code)
567 || (0xf900..=0xfaff).contains(&code)
568 || (0xfe10..=0xfe19).contains(&code)
569 || (0xfe30..=0xfe6b).contains(&code)
570 || (0xff01..=0xff60).contains(&code)
571 || (0xffe0..=0xffe6).contains(&code)
572 || (0x1b000..=0x1b001).contains(&code)
573 || (0x1f200..=0x1f251).contains(&code)
574 || (0x1f300..=0x1f64f).contains(&code)
575 || (0x20000..=0x3fffd).contains(&code))
576}
577
578fn cli_table(head: &[String], columns: &[Vec<Option<String>>]) -> String {
582 let longest = columns.iter().map(Vec::len).max().unwrap_or(0);
583 let mut widths: Vec<usize> = head.iter().map(|h| string_width(h)).collect();
584 let mut rows: Vec<Vec<String>> = vec![Vec::with_capacity(head.len()); longest];
585 for (i, column) in columns.iter().enumerate() {
586 for (j, row) in rows.iter_mut().enumerate() {
587 let value = column.get(j).cloned().flatten().unwrap_or_default();
588 widths[i] = widths[i].max(string_width(&value));
589 row.push(value);
590 }
591 }
592 let render_row = |row: &[String]| -> String {
593 let cells: Vec<String> = row
594 .iter()
595 .zip(&widths)
596 .map(|(cell, w)| format!("{cell}{}", " ".repeat(w.saturating_sub(string_width(cell)))))
597 .collect();
598 format!("│ {} │", cells.join(" │ "))
599 };
600 let divider: Vec<String> = widths.iter().map(|w| "─".repeat(w + 2)).collect();
601 let mut out = format!(
602 "┌{}┐\n{}\n├{}┤\n",
603 divider.join("┬"),
604 render_row(head),
605 divider.join("┼")
606 );
607 for row in &rows {
608 out.push_str(&render_row(row));
609 out.push('\n');
610 }
611 out.push_str(&format!("└{}┘", divider.join("┴")));
612 out
613}