1use std::convert::TryFrom;
6use std::fmt::Write as _;
7use std::ptr::{self, NonNull};
8use std::slice;
9
10#[cfg(feature = "devtools")]
11use devtools_traits::{
12 ConsoleMessage, ConsoleMessageFields, DebuggerValue, FunctionPreview, ObjectPreview,
13 PropertyDescriptor as DevtoolsPropertyDescriptor, ScriptToDevtoolsControlMsg, StackFrame,
14 get_time_stamp,
15};
16use embedder_traits::{ConsoleLogLevel, EmbedderMsg};
17use js::context::JSContext;
18use js::conversions::jsstr_to_string;
19use js::gc::RootedVec;
20use js::jsapi::{self, ESClass, Heap, PropertyDescriptor};
21#[cfg(feature = "devtools")]
22use js::jsapi::{JS_GetFunctionArity, SavedFrameSelfHosted};
23use js::jsval::{Int32Value, JSVal, ObjectValue, UndefinedValue};
24#[cfg(feature = "devtools")]
25use js::realm::CurrentRealm;
26#[cfg(feature = "devtools")]
27use js::rust::wrappers2::{
28 GetArrayLength, GetSavedFrameColumn, GetSavedFrameFunctionDisplayName, GetSavedFrameLine,
29 GetSavedFrameSource, JS_GetElement, JS_GetFunctionDisplayId, JS_GetFunctionId,
30 JS_ValueToFunction, MapEntries, MapSize,
31};
32use js::rust::wrappers2::{
33 GetBuiltinClass, JS_ClearPendingException, JS_Stringify, JS_ValueToSource,
34};
35#[cfg(feature = "devtools")]
36use js::rust::{CapturedJSStack, describe_scripted_caller, for_of};
37use js::rust::{HandleObject, HandleValue, IdVector, ToNumber, ToString};
38#[cfg(feature = "devtools")]
39use script_bindings::codegen::PrototypeList::proto_id_to_name;
40use script_bindings::conversions::get_dom_class;
41use script_bindings::js::{
42 GetPropertyKeys, JS_GetOwnPropertyDescriptorById, JS_GetPropertyById, JS_GetPrototype,
43 JS_IdToValue,
44};
45
46use crate::dom::bindings::codegen::Bindings::ConsoleBinding::consoleMethods;
47#[cfg(feature = "devtools")]
48use crate::dom::bindings::error::report_pending_exception;
49#[cfg(feature = "devtools")]
50use crate::dom::bindings::inheritance::Castable;
51use crate::dom::bindings::str::DOMString;
52use crate::dom::globalscope::GlobalScope;
53#[cfg(feature = "devtools")]
54use crate::dom::workerglobalscope::WorkerGlobalScope;
55
56const MAX_LOG_DEPTH: usize = 10;
58const MAX_LOG_CHILDREN: usize = 15;
60
61#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
63pub(crate) struct Console;
64
65impl Console {
66 fn send_string_message(
68 cx: &mut JSContext,
69 global: &GlobalScope,
70 level: ConsoleLogLevel,
71 message: String,
72 ) {
73 let prefix = global.current_group_label().unwrap_or_default();
74 let formatted_message = format!("{prefix}{message}");
75
76 Self::send_to_embedder(global, level, formatted_message);
77
78 #[cfg(feature = "devtools")]
79 {
80 let console_message =
81 Self::build_message(cx, level, vec![DebuggerValue::StringValue(message)], None);
82 Self::send_to_devtools(global, console_message);
83 }
84
85 let _ = cx;
86 }
87
88 fn method_for_devtools(
90 cx: &mut JSContext,
91 global: &GlobalScope,
92 level: ConsoleLogLevel,
93 messages: Vec<HandleValue>,
94 include_stacktrace: IncludeStackTrace,
95 ) {
96 #[cfg(feature = "devtools")]
97 if global.devtools_chan().is_some() {
98 rooted_vec!(let mut seen);
99 let devtools_arguments = if messages.first().is_none_or(|message| !message.is_string())
100 {
101 messages
102 .iter()
103 .map(|msg| devtools::console_argument_from_handle_value(cx, *msg, &mut seen))
104 .collect()
105 } else {
106 let (formatted, consumed) = apply_sprintf_substitutions(cx, &messages);
107 std::iter::once(DebuggerValue::StringValue(formatted))
108 .chain(messages.iter().skip(consumed).map(|msg| {
109 devtools::console_argument_from_handle_value(cx, *msg, &mut seen)
110 }))
111 .collect()
112 };
113
114 let stacktrace =
115 (include_stacktrace == IncludeStackTrace::Yes).then_some(get_js_stack(cx));
116 Console::send_to_devtools(
117 global,
118 Self::build_message(cx, level, devtools_arguments, stacktrace),
119 );
120 }
121 }
122
123 fn method(
124 cx: &mut JSContext,
125 global: &GlobalScope,
126 level: ConsoleLogLevel,
127 messages: Vec<HandleValue>,
128 include_stacktrace: IncludeStackTrace,
129 ) {
130 let embedder_msg = if !messages.is_empty() && messages[0].is_string() {
134 let (formatted, consumed) = apply_sprintf_substitutions(cx, &messages);
135
136 let embedder_msg = if messages[consumed..].is_empty() {
137 formatted
138 } else {
139 format!(
140 "{formatted} {}",
141 stringify_handle_values(cx, &messages[consumed..])
142 )
143 };
144 embedder_msg.into()
145 } else {
146 stringify_handle_values(cx, &messages)
147 };
148
149 Console::method_for_devtools(cx, global, level, messages, include_stacktrace);
150
151 let prefix = global.current_group_label().unwrap_or_default();
152 let formatted_message = format!("{prefix}{embedder_msg}");
153
154 Self::send_to_embedder(global, level, formatted_message);
155 }
156
157 fn send_to_embedder(global: &GlobalScope, level: ConsoleLogLevel, message: String) {
158 global.send_to_embedder(EmbedderMsg::ShowConsoleApiMessage(
159 global.webview_id(),
160 level,
161 message,
162 ));
163 }
164
165 pub(crate) fn internal_warn(cx: &mut JSContext, global: &GlobalScope, message: String) {
167 Console::send_string_message(cx, global, ConsoleLogLevel::Warn, message);
168 }
169
170 pub(crate) fn internal_error(cx: &mut JSContext, global: &GlobalScope, message: String) {
171 Console::send_string_message(cx, global, ConsoleLogLevel::Error, message);
172 }
173
174 pub(crate) fn error_to_console(global: &GlobalScope, message: String) {
175 global.send_to_embedder(EmbedderMsg::ShowConsoleApiMessage(
176 global.webview_id(),
177 ConsoleLogLevel::Error,
178 message,
179 ));
180 }
181}
182
183#[expect(unsafe_code)]
184fn handle_value_to_string(cx: &mut JSContext, value: HandleValue) -> DOMString {
185 match std::ptr::NonNull::new(unsafe { JS_ValueToSource(cx, value) }) {
186 Some(js_str) => unsafe { jsstr_to_string(cx, js_str) }.into(),
187 None => DOMString::from_static("<error converting value to string>"),
188 }
189}
190
191#[cfg(feature = "devtools")]
192mod devtools {
193 use super::*;
194
195 impl Console {
196 pub(super) fn build_message(
197 cx: &mut JSContext,
198 level: ConsoleLogLevel,
199 arguments: Vec<DebuggerValue>,
200 stacktrace: Option<Vec<StackFrame>>,
201 ) -> ConsoleMessage {
202 let caller = describe_scripted_caller(cx).unwrap_or_default();
203
204 ConsoleMessage {
205 fields: ConsoleMessageFields {
206 level,
207 filename: caller.filename,
208 line_number: caller.line,
209 column_number: caller.col,
210 time_stamp: get_time_stamp(),
211 },
212 arguments,
213 stacktrace,
214 }
215 }
216
217 pub(super) fn send_to_devtools(global: &GlobalScope, message: ConsoleMessage) {
218 if let Some(chan) = global.devtools_chan() {
219 let worker_id = global
220 .downcast::<WorkerGlobalScope>()
221 .map(|worker| worker.worker_id());
222 let devtools_message = ScriptToDevtoolsControlMsg::ConsoleAPI(
223 global.pipeline_id(),
224 message,
225 worker_id,
226 );
227 chan.send(devtools_message).unwrap();
228 }
229 }
230 }
231
232 pub(super) fn console_argument_from_handle_value(
233 cx: &mut JSContext,
234 handle_value: HandleValue,
235 seen: &mut RootedVec<'_, Box<Heap<JSVal>>>,
236 ) -> DebuggerValue {
237 #[expect(unsafe_code)]
238 fn inner(
239 cx: &mut JSContext,
240 handle_value: HandleValue,
241 seen: &mut RootedVec<'_, Box<Heap<JSVal>>>,
242 ) -> Result<DebuggerValue, ()> {
243 if handle_value.is_string() {
244 let js_string = ptr::NonNull::new(handle_value.to_string()).unwrap();
245 let dom_string = unsafe { jsstr_to_string(cx, js_string) };
246 return Ok(DebuggerValue::StringValue(dom_string));
247 }
248
249 if handle_value.is_number() {
250 let number = handle_value.to_number();
251 return Ok(DebuggerValue::NumberValue(number));
252 }
253
254 if handle_value.is_boolean() {
255 let boolean = handle_value.to_boolean();
256 return Ok(DebuggerValue::BooleanValue(boolean));
257 }
258
259 if handle_value.is_object() {
260 if seen
262 .iter()
263 .any(|seen_value| seen_value.get().asBits_ == handle_value.asBits_)
264 {
265 return Ok(DebuggerValue::StringValue("[circular]".into()));
267 }
268
269 seen.push(Heap::boxed(handle_value.get()));
271 rooted!(&in(cx) let object = handle_value.to_object());
272 let console_object = console_object_from_handle_value(cx, handle_value, seen);
273 let prototype = object_prototype_debugger_value(cx, object.handle(), seen);
274 debug_assert_eq!(
275 seen.last().map(|js_value| js_value.get().asBits_),
276 Some(handle_value.asBits_)
277 );
278 seen.pop();
279 let prototype = prototype?;
280
281 if let Some((class, preview)) = console_object {
282 return Ok(DebuggerValue::ObjectValue {
283 actor: None,
284 class,
285 own_property_length: preview.own_properties_length,
286 preview: Some(Box::new(preview)),
287 prototype,
288 });
289 }
290
291 return Err(());
292 }
293
294 let stringified_value = stringify_handle_value(cx, handle_value);
296
297 Ok(DebuggerValue::StringValue(stringified_value.into()))
298 }
299
300 match inner(cx, handle_value, seen) {
301 Ok(arg) => arg,
302 Err(()) => {
303 report_pending_exception(&mut CurrentRealm::assert(cx));
304 DebuggerValue::StringValue("<error>".into())
305 },
306 }
307 }
308
309 #[cfg(feature = "devtools")]
310 fn object_prototype_debugger_value(
311 cx: &mut JSContext,
312 object: HandleObject,
313 seen: &mut RootedVec<'_, Box<Heap<JSVal>>>,
314 ) -> Result<Option<Box<DebuggerValue>>, ()> {
315 rooted!(&in(cx) let mut prototype = ptr::null_mut::<jsapi::JSObject>());
316 if !JS_GetPrototype(cx, object, prototype.handle_mut()) {
317 return Err(());
318 }
319 if prototype.is_null() {
320 return Ok(Some(Box::new(DebuggerValue::NullValue(false))));
321 }
322
323 rooted!(&in(cx) let prototype = ObjectValue(prototype.get()));
324 Ok(Some(Box::new(console_argument_from_handle_value(
325 cx,
326 prototype.handle(),
327 seen,
328 ))))
329 }
330
331 fn accessor_value_from_property_descriptor(descriptor: &PropertyDescriptor) -> DebuggerValue {
332 let value = match (
335 descriptor.hasGetter_() && !descriptor.getter_.is_null(),
336 descriptor.hasSetter_() && !descriptor.setter_.is_null(),
337 ) {
338 (true, true) => "Getter/Setter",
339 (true, false) => "Getter",
340 (false, true) => "Setter",
341 (false, false) => "undefined",
342 };
343 DebuggerValue::StringValue(value.into())
344 }
345
346 #[expect(unsafe_code)]
347 fn console_map_object_from_handle_value(
348 cx: &mut JSContext,
349 handle_object: HandleObject,
350 seen: &mut RootedVec<'_, Box<Heap<JSVal>>>,
351 ) -> Option<(String, ObjectPreview)> {
352 rooted!(&in(cx) let mut iterator = UndefinedValue());
353 if !unsafe { MapEntries(cx, handle_object, iterator.handle_mut()) } {
354 return None;
355 }
356
357 let mut entries = Vec::new();
358 for_of(cx, iterator.handle(), |cx, entry| {
359 if !entry.is_object() {
360 return Err(().into());
361 }
362
363 rooted!(&in(cx) let entry_object = entry.to_object());
364 rooted!(&in(cx) let mut key = UndefinedValue());
365 rooted!(&in(cx) let mut value = UndefinedValue());
366
367 if !unsafe { JS_GetElement(cx, entry_object.handle(), 0, key.handle_mut()) } ||
369 !unsafe { JS_GetElement(cx, entry_object.handle(), 1, value.handle_mut()) }
370 {
371 return Err(().into());
372 }
373
374 entries.push((
375 console_argument_from_handle_value(cx, key.handle(), seen),
376 console_argument_from_handle_value(cx, value.handle(), seen),
377 ));
378
379 Ok(std::ops::ControlFlow::Continue(()))
380 })
381 .ok()?;
382
383 Some((
384 "Map".into(),
385 ObjectPreview {
386 kind: "MapLike".into(),
387 size: Some(unsafe { MapSize(cx, handle_object) }),
388 entries: Some(entries),
389 own_properties_length: Some(0),
390 own_properties: None,
391 function: None,
392 array_length: None,
393 items: None,
394 },
395 ))
396 }
397
398 #[expect(unsafe_code)]
399 fn console_object_from_handle_value(
400 cx: &mut JSContext,
401 handle_value: HandleValue,
402 seen: &mut RootedVec<'_, Box<Heap<JSVal>>>,
403 ) -> Option<(String, ObjectPreview)> {
404 rooted!(&in(cx) let object = handle_value.to_object());
405 let mut object_class = ESClass::Other;
406 if !unsafe { GetBuiltinClass(cx, object.handle(), &mut object_class as *mut _) } {
407 return None;
408 }
409
410 let dom_class = unsafe { get_dom_class(object.get()).ok() };
411 if dom_class.is_none() &&
412 object_class != ESClass::Object &&
413 object_class != ESClass::Array &&
414 object_class != ESClass::Map &&
415 object_class != ESClass::Function
416 {
417 return None;
418 }
419
420 if object_class == ESClass::Map {
421 return console_map_object_from_handle_value(cx, object.handle(), seen);
422 }
423
424 let mut own_properties = Vec::new();
425 let mut items: Vec<(i32, DebuggerValue)> = Vec::new();
426 let mut ids = IdVector::new(cx);
427 if !GetPropertyKeys(
430 cx,
431 object.handle(),
432 jsapi::JSITER_OWNONLY | jsapi::JSITER_SYMBOLS | jsapi::JSITER_HIDDEN,
433 ids.handle_mut(),
434 ) {
435 return None;
436 }
437
438 for id in ids.iter() {
439 rooted!(&in(cx) let id = *id);
440 rooted!(&in(cx) let mut descriptor = PropertyDescriptor::default());
441
442 let mut is_none = false;
443 if !JS_GetOwnPropertyDescriptorById(
444 cx,
445 object.handle(),
446 id.handle(),
447 descriptor.handle_mut(),
448 &mut is_none,
449 ) {
450 return None;
451 }
452 if is_none {
453 continue;
454 }
455
456 let is_accessor = (descriptor.hasGetter_() && !descriptor.getter_.is_null()) ||
459 (descriptor.hasSetter_() && !descriptor.setter_.is_null());
460 let value = if is_accessor {
461 accessor_value_from_property_descriptor(&descriptor)
462 } else {
463 rooted!(&in(cx) let property = descriptor.value_);
464 console_argument_from_handle_value(cx, property.handle(), seen)
465 };
466
467 if object_class == ESClass::Array && id.is_int() {
468 let index = id.to_int();
469 items.push((index, value));
470 continue;
471 }
472
473 let key = if id.is_string() {
474 rooted!(&in(cx) let mut key_value = UndefinedValue());
475 if !JS_IdToValue(cx, id.handle().get(), key_value.handle_mut()) {
476 continue;
477 }
478 rooted!(&in(cx) let js_string = key_value.to_string());
479 let Some(js_string) = NonNull::new(js_string.get()) else {
480 continue;
481 };
482 unsafe { jsstr_to_string(cx, js_string) }
483 } else if id.is_symbol() || id.is_int() {
484 rooted!(&in(cx) let mut key_value = UndefinedValue());
485 if !JS_IdToValue(cx, id.handle().get(), key_value.handle_mut()) {
486 continue;
487 }
488 handle_value_to_string(cx, key_value.handle()).to_string()
489 } else {
490 continue;
491 };
492
493 own_properties.push(DevtoolsPropertyDescriptor {
494 name: key,
495 value,
496 configurable: descriptor.hasConfigurable_() && descriptor.configurable_(),
497 enumerable: descriptor.hasEnumerable_() && descriptor.enumerable_(),
498 writable: !is_accessor && descriptor.hasWritable_() && descriptor.writable_(),
499 is_accessor,
500 });
501 }
502
503 let dom_class_name = dom_class.map_or("Object", |dom_class| {
504 let interface_id = dom_class.interface_chain[dom_class.depth as usize];
505 proto_id_to_name(interface_id as u16)
506 });
507
508 let (class, kind, function, array_length, items) = match object_class {
509 ESClass::Array => {
510 let mut len = 0u32;
511 if !unsafe { GetArrayLength(cx, object.handle(), &mut len) } {
512 return None;
513 }
514 items.sort_by_key(|(index, _)| *index);
515 let ordered: Vec<DebuggerValue> =
516 items.into_iter().map(|(_, value)| value).collect();
517 (
518 "Array".into(),
519 "ArrayLike".into(),
520 None,
521 Some(len),
522 Some(ordered),
523 )
524 },
525 ESClass::Function => {
526 rooted!(&in(cx) let fun = unsafe { JS_ValueToFunction(cx, handle_value) });
527 rooted!(&in(cx) let mut name = std::ptr::null_mut::<jsapi::JSString>());
528 rooted!(&in(cx) let mut display_name = std::ptr::null_mut::<jsapi::JSString>());
529 let arity;
530 unsafe {
531 JS_GetFunctionId(cx, fun.handle(), name.handle_mut());
532 JS_GetFunctionDisplayId(cx, fun.handle(), display_name.handle_mut());
533 arity = JS_GetFunctionArity(fun.get());
534 }
535 let name =
536 ptr::NonNull::new(*name).map(|name| unsafe { jsstr_to_string(cx, name) });
537 let display_name = ptr::NonNull::new(*display_name)
538 .map(|display_name| unsafe { jsstr_to_string(cx, display_name) });
539
540 let global = GlobalScope::from_current_realm(&mut CurrentRealm::assert(cx));
543 let parameter_names = global
544 .debugger_global(cx)
545 .and_then(|debugger| debugger.function_parameter_names(cx, handle_value))
546 .unwrap_or_else(|| (0..arity).map(|i| format!("<arg{i}>")).collect());
547
548 let function = Box::new(FunctionPreview {
549 name,
550 display_name,
551 parameter_names,
552 is_async: None,
553 is_generator: None,
554 });
555 (
556 "Function".into(),
557 "Object".into(),
558 Some(function),
559 None,
560 None,
561 )
562 },
563 _ => (dom_class_name.into(), "Object".into(), None, None, None),
564 };
565
566 Some((
567 class,
568 ObjectPreview {
569 kind,
570 size: None,
571 entries: None,
572 own_properties_length: Some(own_properties.len() as u32),
573 own_properties: Some(own_properties),
574 function,
575 array_length,
576 items,
577 },
578 ))
579 }
580
581 pub(super) fn string_array_debugger_value(strings: &[DOMString]) -> DebuggerValue {
582 let items: Vec<DebuggerValue> = strings
583 .iter()
584 .map(|s| DebuggerValue::StringValue(s.to_string()))
585 .collect();
586 DebuggerValue::ObjectValue {
587 actor: None,
588 class: "Array".into(),
589 own_property_length: Some(0),
590 preview: Some(Box::new(ObjectPreview {
591 kind: "ArrayLike".into(),
592 size: None,
593 entries: None,
594 own_properties_length: Some(0),
595 own_properties: None,
596 function: None,
597 array_length: Some(items.len() as u32),
598 items: Some(items),
599 })),
600 prototype: None,
601 }
602 }
603}
604
605#[expect(unsafe_code)]
606fn stringify_object_from_handle_value(
607 cx: &mut JSContext,
608 value: HandleValue,
609 parents: &mut RootedVec<'_, Box<Heap<JSVal>>>,
610) -> DOMString {
611 rooted!(&in(cx) let mut obj = value.to_object());
612 let mut object_class = ESClass::Other;
613 if !unsafe { GetBuiltinClass(cx, obj.handle(), &mut object_class as *mut _) } {
614 return DOMString::from_static("/* invalid */");
615 }
616 let mut ids = IdVector::new(cx);
617 if !GetPropertyKeys(
618 cx,
619 obj.handle(),
620 jsapi::JSITER_OWNONLY | jsapi::JSITER_SYMBOLS,
621 ids.handle_mut(),
622 ) {
623 return DOMString::from_static("/* invalid */");
624 }
625 let truncate = ids.len() > MAX_LOG_CHILDREN;
626 if object_class != ESClass::Array && object_class != ESClass::Object {
627 if truncate {
628 return DOMString::from_static("…");
629 } else {
630 return handle_value_to_string(cx, value);
631 }
632 }
633
634 let mut explicit_keys = object_class == ESClass::Object;
635 let mut props = Vec::with_capacity(ids.len());
636 for id in ids.iter().take(MAX_LOG_CHILDREN) {
637 rooted!(&in(cx) let id = *id);
638 rooted!(&in(cx) let mut desc = PropertyDescriptor::default());
639
640 let mut is_none = false;
641 if !JS_GetOwnPropertyDescriptorById(
642 cx,
643 obj.handle(),
644 id.handle(),
645 desc.handle_mut(),
646 &mut is_none,
647 ) {
648 return DOMString::from_static("/* invalid */");
649 }
650
651 rooted!(&in(cx) let mut property = UndefinedValue());
652 if !JS_GetPropertyById(cx, obj.handle(), id.handle(), property.handle_mut()) {
653 return DOMString::from_static("/* invalid */");
654 }
655
656 if !explicit_keys {
657 if id.is_int() {
658 if let Ok(id_int) = usize::try_from(id.to_int()) {
659 explicit_keys = props.len() != id_int;
660 } else {
661 explicit_keys = false;
662 }
663 } else {
664 explicit_keys = false;
665 }
666 }
667 let value_string = stringify_handle_value_inner(cx, property.handle(), parents);
668 if explicit_keys {
669 let key = if id.is_string() || id.is_symbol() || id.is_int() {
670 rooted!(&in(cx) let mut key_value = UndefinedValue());
671 if !JS_IdToValue(cx, id.handle().get(), key_value.handle_mut()) {
672 return DOMString::from_static("/* invalid */");
673 }
674 handle_value_to_string(cx, key_value.handle())
675 } else {
676 return DOMString::from_static("/* invalid */");
677 };
678 props.push(format!("{}: {}", key, value_string,));
679 } else {
680 props.push(String::from(value_string));
681 }
682 }
683 if truncate {
684 props.push("…".to_string());
685 }
686 if object_class == ESClass::Array {
687 DOMString::from(format!("[{}]", itertools::join(props, ", ")))
688 } else {
689 DOMString::from(format!("{{{}}}", itertools::join(props, ", ")))
690 }
691}
692
693fn stringify_handle_value_inner(
694 cx: &mut JSContext,
695 value: HandleValue,
696 parents: &mut RootedVec<'_, Box<Heap<JSVal>>>,
697) -> DOMString {
698 if parents.len() >= MAX_LOG_DEPTH {
699 return DOMString::from_static("...");
700 }
701 if parents
702 .iter()
703 .any(|parent| parent.get().asBits_ == value.asBits_)
704 {
705 return DOMString::from_static("[circular]");
706 }
707 if value.is_undefined() {
708 return DOMString::from_static("undefined");
710 } else if !value.is_object() {
711 return handle_value_to_string(cx, value);
712 }
713
714 if let Some(repr) = maybe_stringify_dom_object(cx, value) {
715 return repr;
716 }
717
718 parents.push(Heap::boxed(value.get()));
720 let result = stringify_object_from_handle_value(cx, value, parents);
721 parents.pop();
722 result
723}
724
725#[expect(unsafe_code)]
726pub(crate) fn stringify_handle_value(cx: &mut JSContext, message: HandleValue) -> DOMString {
727 if message.is_string() {
728 let jsstr = std::ptr::NonNull::new(message.to_string()).unwrap();
729 return unsafe { jsstr_to_string(cx, jsstr) }.into();
730 }
731
732 rooted_vec!(let mut parents);
733 stringify_handle_value_inner(cx, message, &mut parents)
734}
735
736#[expect(unsafe_code)]
737fn maybe_stringify_dom_object(cx: &mut JSContext, value: HandleValue) -> Option<DOMString> {
738 rooted!(&in(cx) let obj = value.to_object());
743 let is_dom_class = unsafe { get_dom_class(obj.get()).is_ok() };
744 if !is_dom_class {
745 return None;
746 }
747 rooted!(&in(cx) let class_name = unsafe { ToString(cx, value) });
748 let Some(class_name) = NonNull::new(class_name.get()) else {
749 return Some(DOMString::from_static(
750 "<error converting DOM object to string>",
751 ));
752 };
753 let class_name = unsafe { jsstr_to_string(cx, class_name) }
754 .replace("[object ", "")
755 .replace("]", "");
756 let mut repr = format!("{} ", class_name);
757 rooted!(&in(cx) let mut value = value.get());
758
759 #[expect(unsafe_code)]
760 unsafe extern "C" fn stringified(
761 string: *const u16,
762 len: u32,
763 data: *mut std::ffi::c_void,
764 ) -> bool {
765 let s = data as *mut String;
766 let string_chars = unsafe { slice::from_raw_parts(string, len as usize) };
767 unsafe { (*s).push_str(&String::from_utf16_lossy(string_chars)) };
768 true
769 }
770
771 rooted!(&in(cx) let space = Int32Value(2));
772 let stringify_result = unsafe {
773 JS_Stringify(
774 cx,
775 value.handle_mut(),
776 HandleObject::null(),
777 space.handle(),
778 Some(stringified),
779 &mut repr as *mut String as *mut _,
780 )
781 };
782 if !stringify_result {
783 return Some(DOMString::from_static(
784 "<error converting DOM object to string>",
785 ));
786 }
787 Some(repr.into())
788}
789
790#[expect(unsafe_code)]
798fn apply_sprintf_substitutions(cx: &mut JSContext, messages: &[HandleValue]) -> (String, usize) {
799 debug_assert!(!messages.is_empty() && messages[0].is_string());
800
801 let js_string = ptr::NonNull::new(messages[0].to_string()).unwrap();
802 let format_string = unsafe { jsstr_to_string(cx, js_string) };
803
804 let mut result = String::with_capacity(format_string.len());
805 let mut arg_index = 1usize;
806 let mut chars = format_string.chars().peekable();
807
808 while let Some(c) = chars.next() {
809 if c != '%' {
810 result.push(c);
811 continue;
812 }
813
814 match chars.peek() {
815 Some('s') => {
816 chars.next();
817 if arg_index < messages.len() {
818 result.push_str(&stringify_handle_value(cx, messages[arg_index]).str());
819 arg_index += 1;
820 } else {
821 result.push_str("%s");
822 }
823 },
824 Some('d') | Some('i') => {
825 let spec = chars.next().unwrap();
826 if arg_index < messages.len() {
827 let num = unsafe { ToNumber(cx, messages[arg_index]) };
828 if num.is_err() {
829 unsafe { JS_ClearPendingException(cx) };
830 }
831 arg_index += 1;
832 format_integer_substitution(&mut result, num);
833 } else {
834 result.push('%');
835 result.push(spec);
836 }
837 },
838 Some('f') => {
839 chars.next();
840 if arg_index < messages.len() {
841 let num = unsafe { ToNumber(cx, messages[arg_index]) };
842 if num.is_err() {
843 unsafe { JS_ClearPendingException(cx) };
844 }
845 arg_index += 1;
846 format_float_substitution(&mut result, num);
847 } else {
848 result.push_str("%f");
849 }
850 },
851 Some('o') | Some('O') => {
852 let spec = chars.next().unwrap();
853 if arg_index < messages.len() {
854 result.push_str(&stringify_handle_value(cx, messages[arg_index]).str());
855 arg_index += 1;
856 } else {
857 result.push('%');
858 result.push(spec);
859 }
860 },
861 Some('c') => {
862 chars.next();
863 if arg_index < messages.len() {
864 arg_index += 1; }
866 },
867 Some('%') => {
868 chars.next();
869 result.push('%');
870 },
871 _ => {
872 result.push('%');
873 },
874 }
875 }
876
877 (result, arg_index)
878}
879
880fn format_integer_substitution(result: &mut String, num: Result<f64, ()>) {
881 match num {
882 Ok(n) if n.is_nan() => result.push_str("NaN"),
883 Ok(n) if n == f64::INFINITY => result.push_str("Infinity"),
884 Ok(n) if n == f64::NEG_INFINITY => result.push_str("-Infinity"),
885 Ok(n) => write!(result, "{}", n.trunc() as i64).unwrap(),
886 Err(_) => result.push_str("NaN"),
887 }
888}
889
890fn format_float_substitution(result: &mut String, num: Result<f64, ()>) {
891 match num {
892 Ok(n) if n.is_nan() => result.push_str("NaN"),
893 Ok(n) if n == f64::INFINITY => result.push_str("Infinity"),
894 Ok(n) if n == f64::NEG_INFINITY => result.push_str("-Infinity"),
895 Ok(n) => write!(result, "{n}").unwrap(),
896 Err(_) => result.push_str("NaN"),
897 }
898}
899
900fn stringify_handle_values(cx: &mut JSContext, messages: &[HandleValue]) -> DOMString {
901 DOMString::from(itertools::join(
902 messages.iter().map(|msg| stringify_handle_value(cx, *msg)),
903 " ",
904 ))
905}
906
907#[cfg(feature = "devtools")]
910fn stringify_debugger_value(value: &DebuggerValue) -> String {
911 match value {
912 DebuggerValue::VoidValue => "undefined".into(),
913 DebuggerValue::NullValue(_) => "null".into(),
914 DebuggerValue::BooleanValue(value) => value.to_string(),
915 DebuggerValue::NumberValue(value) => value.to_string(),
916 DebuggerValue::StringValue(value) => value.clone(),
917 DebuggerValue::ObjectValue { class, preview, .. } => {
918 let Some(preview) = preview else {
919 return class.clone();
920 };
921
922 if preview.kind == "ArrayLike" {
923 let mut items = preview
924 .items
925 .as_ref()
926 .map(|items| {
927 items
928 .iter()
929 .take(MAX_LOG_CHILDREN)
930 .map(stringify_debugger_value)
931 .collect::<Vec<_>>()
932 })
933 .unwrap_or_default();
934 if preview
935 .array_length
936 .is_some_and(|length| length as usize > items.len())
937 {
938 items.push("...".into());
939 }
940 return format!("[{}]", itertools::join(items, ", "));
941 }
942
943 let mut properties = preview
944 .own_properties
945 .as_ref()
946 .map(|properties| {
947 properties
948 .iter()
949 .take(MAX_LOG_CHILDREN)
950 .map(|property| {
951 format!(
952 "{}: {}",
953 property.name,
954 stringify_debugger_value(&property.value)
955 )
956 })
957 .collect::<Vec<_>>()
958 })
959 .unwrap_or_default();
960 if preview
961 .own_properties_length
962 .is_some_and(|length| length as usize > properties.len())
963 {
964 properties.push("...".into());
965 }
966 format!("{class} {{{}}}", itertools::join(properties, ", "))
967 },
968 }
969}
970
971#[derive(Default)]
972pub struct ConsoleTable {
973 pub columns: Vec<String>,
975 pub rows: Vec<TableRow>,
976}
977
978pub struct TableRow {
979 pub index: String,
980 pub cells: Vec<(String, String)>,
982 pub value: Option<String>,
984}
985
986impl ConsoleTable {
987 pub fn render(&self) -> String {
988 let has_values = self.rows.iter().any(|row| row.value.is_some());
989
990 let mut headers = vec!["(index)".to_string()];
991 headers.extend(self.columns.iter().cloned());
992 if has_values {
993 headers.push("Values".into());
994 }
995
996 let grid: Vec<Vec<String>> = self
997 .rows
998 .iter()
999 .map(|row| {
1000 let mut line = vec![row.index.clone()];
1001 for column in &self.columns {
1002 let cell = row
1003 .cells
1004 .iter()
1005 .find(|(key, _)| key == column)
1006 .map(|(_, v)| v.clone())
1007 .unwrap_or_default();
1008 line.push(cell);
1009 }
1010 if has_values {
1011 line.push(row.value.clone().unwrap_or_default());
1012 }
1013 line
1014 })
1015 .collect();
1016
1017 let column_widths: Vec<usize> = (0..headers.len())
1018 .map(|i| {
1019 std::iter::once(&headers[i])
1020 .chain(grid.iter().map(|row| &row[i]))
1021 .map(|s| s.chars().count())
1022 .max()
1023 .unwrap_or(0)
1024 })
1025 .collect();
1026
1027 let border = |left: &str, mid: &str, right: &str| {
1028 let segments: Vec<String> = column_widths.iter().map(|w| "─".repeat(w + 2)).collect();
1029 format!("{left}{}{right}", segments.join(mid))
1030 };
1031 let line = |cells: &[String]| {
1032 let padded: Vec<String> = cells
1033 .iter()
1034 .zip(&column_widths)
1035 .map(|(cell, &column_width)| {
1036 let pad_width = column_width.saturating_sub(cell.chars().count());
1038 format!(" {cell}{} ", " ".repeat(pad_width))
1039 })
1040 .collect();
1041 format!("│{}│", padded.join("│"))
1042 };
1043
1044 let mut out = vec![border("┌", "┬", "┐"), line(&headers), border("├", "┼", "┤")];
1045 out.extend(grid.iter().map(|row| line(row)));
1046 out.push(border("└", "┴", "┘"));
1047 out.join("\n")
1048 }
1049}
1050
1051fn for_each_own_property(
1054 cx: &mut JSContext,
1055 obj: HandleObject,
1056 mut f: impl FnMut(&mut JSContext, String, HandleValue),
1057) -> bool {
1058 let mut ids = IdVector::new(cx);
1059 if !GetPropertyKeys(cx, obj, jsapi::JSITER_OWNONLY, ids.handle_mut()) {
1061 return false;
1062 }
1063 for id in ids.iter() {
1064 rooted!(&in(cx) let id = *id);
1065 rooted!(&in(cx) let mut key = UndefinedValue());
1066 if !JS_IdToValue(cx, id.handle().get(), key.handle_mut()) {
1067 return false;
1068 }
1069 let key = stringify_handle_value(cx, key.handle()).to_string();
1070
1071 rooted!(&in(cx) let mut value = UndefinedValue());
1072 if !JS_GetPropertyById(cx, obj, id.handle(), value.handle_mut()) {
1074 return false;
1075 }
1076 f(cx, key, value.handle());
1077 }
1078 true
1079}
1080
1081fn table_cell_string(cx: &mut JSContext, value: HandleValue) -> String {
1082 if value.is_string() {
1083 handle_value_to_string(cx, value).to_string() } else {
1085 stringify_handle_value(cx, value).to_string()
1086 }
1087}
1088
1089#[expect(unsafe_code)]
1090fn build_console_table(
1091 cx: &mut JSContext,
1092 data: HandleValue,
1093 properties: Option<&[DOMString]>,
1094) -> Option<ConsoleTable> {
1095 if !data.is_object() {
1096 return None;
1097 }
1098 let filter: Option<Vec<String>> =
1099 properties.map(|props| props.iter().map(|p| p.to_string()).collect());
1100
1101 let mut table = ConsoleTable::default();
1102 if let Some(filter) = &filter {
1103 table.columns = filter.clone();
1105 }
1106
1107 rooted!(&in(cx) let data_obj = data.to_object());
1108 let mut failed = false;
1109 let ok = for_each_own_property(cx, data_obj.handle(), |cx, index, row| {
1110 let mut cells = Vec::new();
1111 let mut value = None;
1112
1113 if row.is_object() {
1114 rooted!(&in(cx) let row_obj = row.to_object());
1115 let columns = &mut table.columns;
1116 let ok = for_each_own_property(cx, row_obj.handle(), |cx, key, cell| {
1117 match &filter {
1118 Some(filter) if !filter.contains(&key) => return,
1119 None if !columns.contains(&key) => columns.push(key.clone()),
1120 _ => {},
1121 }
1122 cells.push((key, table_cell_string(cx, cell)));
1123 });
1124 failed |= !ok;
1125 } else {
1126 value = Some(table_cell_string(cx, row));
1127 }
1128
1129 table.rows.push(TableRow {
1130 index,
1131 cells,
1132 value,
1133 });
1134 });
1135
1136 if !ok || failed {
1137 unsafe { JS_ClearPendingException(cx) };
1138 return None;
1139 }
1140 Some(table)
1141}
1142
1143#[derive(Debug, Eq, PartialEq)]
1144enum IncludeStackTrace {
1145 Yes,
1146 No,
1147}
1148
1149impl consoleMethods<crate::DomTypeHolder> for Console {
1150 fn Log(cx: &mut JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
1152 Console::method(
1153 cx,
1154 global,
1155 ConsoleLogLevel::Log,
1156 messages,
1157 IncludeStackTrace::No,
1158 );
1159 }
1160
1161 fn Table(
1163 cx: &mut JSContext,
1164 global: &GlobalScope,
1165 tabular_data: HandleValue,
1166 properties: Option<Vec<DOMString>>,
1167 ) {
1168 let Some(table) = build_console_table(cx, tabular_data, properties.as_deref()) else {
1169 Console::method(
1171 cx,
1172 global,
1173 ConsoleLogLevel::Log,
1174 vec![tabular_data],
1175 IncludeStackTrace::No,
1176 );
1177 return;
1178 };
1179
1180 #[cfg(feature = "devtools")]
1181 {
1182 rooted_vec!(let mut seen);
1183 let data = devtools::console_argument_from_handle_value(cx, tabular_data, &mut seen);
1184
1185 let level = if matches!(data, DebuggerValue::ObjectValue { .. }) {
1188 ConsoleLogLevel::Table
1189 } else {
1190 ConsoleLogLevel::Log
1191 };
1192
1193 let mut arguments = vec![data];
1194 if let Some(properties) = &properties {
1195 arguments.push(devtools::string_array_debugger_value(properties));
1196 }
1197
1198 Console::send_to_devtools(global, Self::build_message(cx, level, arguments, None));
1199 }
1200
1201 let prefix = global.current_group_label().unwrap_or_default();
1202 Self::send_to_embedder(
1203 global,
1204 ConsoleLogLevel::Table,
1205 format!("{prefix}\n{}", table.render()),
1206 );
1207 }
1208
1209 fn Clear(global: &GlobalScope) {
1211 #[cfg(feature = "devtools")]
1212 if let Some(chan) = global.devtools_chan() {
1213 let worker_id = global
1214 .downcast::<WorkerGlobalScope>()
1215 .map(|worker| worker.worker_id());
1216 let devtools_message =
1217 ScriptToDevtoolsControlMsg::ClearConsole(global.pipeline_id(), worker_id);
1218 if let Err(error) = chan.send(devtools_message) {
1219 log::warn!("Error sending clear message to devtools: {error:?}");
1220 }
1221 }
1222
1223 let _ = global;
1224 }
1225
1226 fn Debug(cx: &mut JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
1228 Console::method(
1229 cx,
1230 global,
1231 ConsoleLogLevel::Debug,
1232 messages,
1233 IncludeStackTrace::No,
1234 );
1235 }
1236
1237 fn Info(cx: &mut JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
1239 Console::method(
1240 cx,
1241 global,
1242 ConsoleLogLevel::Info,
1243 messages,
1244 IncludeStackTrace::No,
1245 );
1246 }
1247
1248 fn Warn(cx: &mut JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
1250 Console::method(
1251 cx,
1252 global,
1253 ConsoleLogLevel::Warn,
1254 messages,
1255 IncludeStackTrace::No,
1256 );
1257 }
1258
1259 fn Error(cx: &mut JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
1261 Console::method(
1262 cx,
1263 global,
1264 ConsoleLogLevel::Error,
1265 messages,
1266 IncludeStackTrace::No,
1267 );
1268 }
1269
1270 fn Trace(cx: &mut JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
1272 Console::method(
1273 cx,
1274 global,
1275 ConsoleLogLevel::Trace,
1276 messages,
1277 IncludeStackTrace::Yes,
1278 );
1279 }
1280
1281 fn Dir(
1283 cx: &mut js::context::JSContext,
1284 global: &GlobalScope,
1285 item: HandleValue,
1286 _options: Option<*mut jsapi::JSObject>,
1287 ) {
1288 #[cfg(feature = "devtools")]
1289 {
1290 rooted_vec!(let mut seen);
1292 let argument = devtools::console_argument_from_handle_value(cx, item, &mut seen);
1293 let prefix = global.current_group_label().unwrap_or_default();
1294 Console::send_to_devtools(
1296 global,
1297 Self::build_message(cx, ConsoleLogLevel::Dir, vec![argument.clone()], None),
1298 );
1299 Self::send_to_embedder(
1300 global,
1301 ConsoleLogLevel::Dir,
1302 format!("{prefix}{}", stringify_debugger_value(&argument)),
1303 );
1304 }
1305
1306 #[cfg(not(feature = "devtools"))]
1307 {
1308 let prefix = global.current_group_label().unwrap_or_default();
1309 Self::send_to_embedder(
1310 global,
1311 ConsoleLogLevel::Dir,
1312 format!("{prefix}{}", stringify_handle_value(cx, item)),
1313 );
1314 }
1315 }
1316
1317 fn Dirxml(cx: &mut JSContext, global: &GlobalScope, data: Vec<HandleValue>) {
1319 Console::method(
1328 cx,
1329 global,
1330 ConsoleLogLevel::Log,
1331 data,
1332 IncludeStackTrace::No,
1333 );
1334 }
1335
1336 fn Assert(
1338 cx: &mut JSContext,
1339 global: &GlobalScope,
1340 condition: bool,
1341 messages: Vec<HandleValue>,
1342 ) {
1343 if !condition {
1344 let message = format!(
1345 "Assertion failed: {}",
1346 stringify_handle_values(cx, &messages)
1347 );
1348
1349 Console::send_string_message(cx, global, ConsoleLogLevel::Log, message);
1350 }
1351 }
1352
1353 fn Time(cx: &mut JSContext, global: &GlobalScope, label: DOMString) {
1355 if let Ok(()) = global.time(label.clone()) {
1356 let message = format!("{label}: timer started");
1357 Console::send_string_message(cx, global, ConsoleLogLevel::Log, message);
1358 }
1359 }
1360
1361 fn TimeLog(cx: &mut JSContext, global: &GlobalScope, label: DOMString, data: Vec<HandleValue>) {
1363 if let Ok(delta) = global.time_log(&label) {
1364 let message = format!("{label}: {delta}ms {}", stringify_handle_values(cx, &data));
1365
1366 Console::send_string_message(cx, global, ConsoleLogLevel::Log, message);
1367 }
1368 }
1369
1370 fn TimeEnd(cx: &mut JSContext, global: &GlobalScope, label: DOMString) {
1372 if let Ok(delta) = global.time_end(&label) {
1373 let message = format!("{label}: {delta}ms");
1374
1375 Console::send_string_message(cx, global, ConsoleLogLevel::Log, message);
1376 }
1377 }
1378
1379 fn Group(cx: &mut JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
1381 global.push_console_group(stringify_handle_values(cx, &messages));
1382 }
1383
1384 fn GroupCollapsed(cx: &mut JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
1386 global.push_console_group(stringify_handle_values(cx, &messages));
1387 }
1388
1389 fn GroupEnd(global: &GlobalScope) {
1391 global.pop_console_group();
1392 }
1393
1394 fn Count(cx: &mut JSContext, global: &GlobalScope, label: DOMString) {
1396 let count = global.increment_console_count(&label);
1397 let message = format!("{label}: {count}");
1398
1399 Console::send_string_message(cx, global, ConsoleLogLevel::Log, message);
1400 }
1401
1402 fn CountReset(cx: &mut JSContext, global: &GlobalScope, label: DOMString) {
1404 if global.reset_console_count(&label).is_err() {
1405 Self::internal_warn(cx, global, format!("Counter “{label}” doesn’t exist."))
1406 }
1407 }
1408}
1409
1410#[cfg(feature = "devtools")]
1411#[expect(unsafe_code)]
1412fn get_js_stack(cx: &mut JSContext) -> Vec<StackFrame> {
1413 const MAX_FRAME_COUNT: u32 = 128;
1414
1415 let mut frames = vec![];
1416 rooted!(&in(cx) let mut handle = ptr::null_mut());
1417 let captured_js_stack = unsafe { CapturedJSStack::new(cx, handle, Some(MAX_FRAME_COUNT)) };
1418 let Some(mut captured_js_stack) = captured_js_stack else {
1419 return frames;
1420 };
1421
1422 captured_js_stack.for_each_stack_frame(|cx, frame| {
1423 rooted!(&in(cx) let mut result: *mut jsapi::JSString = ptr::null_mut());
1424
1425 unsafe {
1427 GetSavedFrameFunctionDisplayName(
1428 cx,
1429 ptr::null_mut(),
1430 frame,
1431 result.handle_mut(),
1432 SavedFrameSelfHosted::Include,
1433 );
1434 }
1435 let function_name = if let Some(nonnull_result) = ptr::NonNull::new(*result) {
1436 unsafe { jsstr_to_string(cx, nonnull_result) }
1437 } else {
1438 "<anonymous>".into()
1439 };
1440
1441 result.set(ptr::null_mut());
1443 unsafe {
1444 GetSavedFrameSource(
1445 cx,
1446 ptr::null_mut(),
1447 frame,
1448 result.handle_mut(),
1449 SavedFrameSelfHosted::Include,
1450 );
1451 }
1452 let filename = if let Some(nonnull_result) = ptr::NonNull::new(*result) {
1453 unsafe { jsstr_to_string(cx, nonnull_result) }
1454 } else {
1455 "<anonymous>".into()
1456 };
1457
1458 let mut line_number = 0;
1460 unsafe {
1461 GetSavedFrameLine(
1462 cx,
1463 ptr::null_mut(),
1464 frame,
1465 &mut line_number,
1466 SavedFrameSelfHosted::Include,
1467 );
1468 }
1469
1470 let mut column_number = jsapi::JS::TaggedColumnNumberOneOrigin { value_: 0 };
1471 unsafe {
1472 GetSavedFrameColumn(
1473 cx,
1474 ptr::null_mut(),
1475 frame,
1476 &mut column_number,
1477 SavedFrameSelfHosted::Include,
1478 );
1479 }
1480 let frame = StackFrame {
1481 filename,
1482 function_name,
1483 line_number,
1484 column_number: column_number.value_,
1485 };
1486
1487 frames.push(frame);
1488 });
1489
1490 frames
1491}