Skip to content

Truly independent web browser

LibJS+WebContent: Bound console previews without invoking getters

sideshowbarker08ecf64883f5
diff --git a/Libraries/LibJS/Print.cpp b/Libraries/LibJS/Print.cpp
index fd11df4a0c2..689c7308f29 100644
--- a/Libraries/LibJS/Print.cpp
+++ b/Libraries/LibJS/Print.cpp
@@ -50,7 +50,7 @@ ErrorOr<void> print(Value value, PrintContext& print_context)
PrintedBytesDestination destination { .print_context = print_context, .bytes_for_the_builder = {}, .stream_error = {} };
JSByteSink sink { .context = &destination, .append = append_printed_bytes };
- if (!js_console_print_value(vm_to_abi(print_context.vm), value_to_abi(value), &sink, print_context.strip_ansi, print_context.raw_strings))
+ if (!js_console_print_value(vm_to_abi(print_context.vm), value_to_abi(value), &sink, print_context.strip_ansi, print_context.raw_strings, print_context.compact))
return destination.stream_error.release_value();
if (print_context.builder) {
diff --git a/Libraries/LibJS/Print.h b/Libraries/LibJS/Print.h
index 6de15dcce35..4c684e0755b 100644
--- a/Libraries/LibJS/Print.h
+++ b/Libraries/LibJS/Print.h
@@ -27,6 +27,7 @@ struct PrintContext {
AK::Utf16StringBuilder* builder { nullptr };
bool strip_ansi { false };
bool raw_strings { false };
+ bool compact { false };
};
JS_API ErrorOr<void> print(JS::Value value, PrintContext&);
diff --git a/Libraries/LibJS/Rust/src/console.rs b/Libraries/LibJS/Rust/src/console.rs
index 46c245b4553..9720b6ef259 100644
--- a/Libraries/LibJS/Rust/src/console.rs
+++ b/Libraries/LibJS/Rust/src/console.rs
@@ -1232,7 +1232,11 @@ impl ConsoleClient {
pub fn generically_format_values(&self, vm: &Vm, values: &MarkedVec<'_, Value>) -> ThrowCompletionOr<Utf16String> {
let mut builder: Vec<u8> = Vec::new();
let mut first = true;
- for index in 0..values.len() {
+ for index in 0..values.len().min(100) {
+ if builder.len() >= 8192 {
+ builder.extend_from_slice(b" ...");
+ break;
+ }
let value = values.get(index).expect("the index is in bounds");
if !first {
builder.push(b' ');
@@ -1242,8 +1246,21 @@ impl ConsoleClient {
stream: &mut builder,
strip_ansi: true,
raw_strings: false,
+ compact: true,
};
print(value, &mut context).expect("printing into a buffer succeeds");
+ if builder.len() > 8192 {
+ let mut end = 8192;
+ while builder[end] & 0xc0 == 0x80 {
+ end -= 1;
+ }
+ builder.truncate(end);
+ builder.extend_from_slice(b" ...");
+ break;
+ }
+ if index == 99 && values.len() > 100 {
+ builder.extend_from_slice(b" ...");
+ }
first = false;
}
Ok(utf16_from_wtf8(&builder).map_or_else(
diff --git a/Libraries/LibJS/Rust/src/embedding/console.rs b/Libraries/LibJS/Rust/src/embedding/console.rs
index 8a2f0063c8c..bd23e2313cc 100644
--- a/Libraries/LibJS/Rust/src/embedding/console.rs
+++ b/Libraries/LibJS/Rust/src/embedding/console.rs
@@ -237,7 +237,8 @@ impl io::Write for ByteSinkWriter<'_> {
/// JS::print(): writes the value to the sink the way the js REPL shows it, as UTF-8 in which lone surrogates are
/// encoded on their own, in ANSI colors unless `strip_ansi` is set, and with strings quoted and escaped unless
-/// `raw_strings` is set. Returns false if the sink refused bytes, which ends the printing. The sink may run JavaScript,
+/// `raw_strings` is set. With `compact`, writes a bounded preview without looking up properties. Returns false if the
+/// sink refused bytes, which ends the printing. The sink may run JavaScript,
/// even JavaScript that changes the value being printed. Only on the VM's thread.
///
/// # Safety
@@ -250,6 +251,7 @@ pub unsafe extern "C" fn js_console_print_value(
sink: *const JSByteSink,
strip_ansi: bool,
raw_strings: bool,
+ compact: bool,
) -> bool {
// SAFETY: The caller passes a live VM.
let vm = unsafe { vm_from_abi(vm) };
@@ -261,6 +263,7 @@ pub unsafe extern "C" fn js_console_print_value(
stream: &mut writer,
strip_ansi,
raw_strings,
+ compact,
};
print(Value::from_bits(value), &mut print_context).is_ok()
}
diff --git a/Libraries/LibJS/Rust/src/runtime/console_preview.rs b/Libraries/LibJS/Rust/src/runtime/console_preview.rs
new file mode 100644
index 00000000000..b47475c41d2
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/runtime/console_preview.rs
@@ -0,0 +1,344 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::ops::ControlFlow;
+
+use crate::interpreter::vm::Vm;
+use crate::layout::value::Value;
+use crate::runtime::array::Array;
+use crate::runtime::boolean_object::BooleanObject;
+use crate::runtime::date::Date;
+use crate::runtime::date_prototype::to_date_string;
+use crate::runtime::ecmascript_function_object::EcmascriptFunctionObject;
+use crate::runtime::error::Error;
+use crate::runtime::map::Map;
+use crate::runtime::native_function::NativeFunction;
+use crate::runtime::number_object::NumberObject;
+use crate::runtime::promise::{Promise, PromiseState};
+use crate::runtime::set::Set;
+use crate::runtime::shared_function_instance_data::FunctionKind;
+use crate::runtime::string_object::StringObject;
+use crate::utf16::Utf16View;
+
+const MAX_BYTES: usize = 8192;
+const MAX_STRING_LENGTH: usize = 1024;
+const MAX_ITEMS: usize = 10;
+const MAX_DEPTH: usize = 2;
+
+// Console output is a preview. Read stored values directly, without property lookup, so logging can't run getters
+// or proxy traps. Limits apply before reading children or converting strings, including for terminal output.
+struct Preview<'a> {
+ vm: &'a Vm,
+ text: String,
+ truncated: bool,
+}
+
+impl Preview<'_> {
+ fn full(&self) -> bool {
+ self.truncated || self.text.len() >= MAX_BYTES
+ }
+
+ fn append(&mut self, text: &str) {
+ if self.full() {
+ return;
+ }
+ let mut end = text.len().min(MAX_BYTES - self.text.len());
+ while !text.is_char_boundary(end) {
+ end -= 1;
+ }
+ self.text.push_str(&text[..end]);
+ self.truncated = end < text.len();
+ }
+
+ fn string(&mut self, text: Utf16View<'_>, quoted: bool) {
+ if quoted {
+ self.append("\"");
+ }
+ let length = text.length_in_code_units().min(MAX_STRING_LENGTH);
+ for code_point in text.substring_view(0, length).to_utf8().chars() {
+ if self.full() {
+ break;
+ }
+ match code_point {
+ '\n' if quoted => self.append("\\n"),
+ '\r' if quoted => self.append("\\r"),
+ '\t' if quoted => self.append("\\t"),
+ '\\' if quoted => self.append("\\\\"),
+ '"' if quoted => self.append("\\\""),
+ _ => self.append(code_point.encode_utf8(&mut [0; 4])),
+ }
+ }
+ if length < text.length_in_code_units() {
+ self.append("...");
+ }
+ if quoted {
+ self.append("\"");
+ }
+ }
+
+ fn value(&mut self, value: Value, depth: usize, raw_strings: bool) {
+ if self.full() {
+ return;
+ }
+ if value.is_accessor() {
+ self.append("[Getter/Setter]");
+ return;
+ }
+ if value.is_empty() {
+ self.append("<empty>");
+ return;
+ }
+ if value.is_string() {
+ self.string(Utf16View::of_string(&value.as_string().utf16_string()), !raw_strings);
+ return;
+ }
+ if value.is_bigint() && value.as_bigint().big_integer().bits() > 4096 {
+ self.append("BigInt {...}");
+ return;
+ }
+ if value.is_symbol() {
+ self.append("Symbol(");
+ if let Some(description) = value.as_symbol().description() {
+ self.string(Utf16View::of_string(description), false);
+ }
+ self.append(")");
+ return;
+ }
+ if value.is_number() && value.as_f64() == 0.0 && value.as_f64().is_sign_negative() {
+ self.append("-0");
+ return;
+ }
+ if !value.is_object() {
+ self.string(
+ Utf16View::of_string(&value.to_utf16_string_without_side_effects()),
+ false,
+ );
+ return;
+ }
+
+ let object = value.as_object();
+
+ // Built-ins whose value lives in an internal slot show that value, which reading the slot can't change.
+ if object.is_function() {
+ let name = if let Some(function) = object.downcast::<EcmascriptFunctionObject>() {
+ self.append(match function.kind() {
+ FunctionKind::Normal => "Function",
+ FunctionKind::Generator => "GeneratorFunction",
+ FunctionKind::Async => "AsyncFunction",
+ FunctionKind::AsyncGenerator => "AsyncGeneratorFunction",
+ });
+ Some(function.name())
+ } else {
+ self.append(object.class().class_name());
+ object.downcast::<NativeFunction>().map(|function| function.name())
+ };
+ if let Some(name) = name
+ && !name.is_empty()
+ {
+ self.append(" ");
+ self.string(Utf16View::of_fly_string(&name), false);
+ }
+ return;
+ }
+ if let Some(boolean_object) = object.downcast::<BooleanObject>() {
+ self.append("Boolean ");
+ self.value(Value::from_bool(boolean_object.boolean()), depth + 1, false);
+ return;
+ }
+ if let Some(number_object) = object.downcast::<NumberObject>() {
+ self.append("Number ");
+ self.value(Value::from_f64(number_object.number()), depth + 1, false);
+ return;
+ }
+ if let Some(string_object) = object.downcast::<StringObject>() {
+ self.append("String ");
+ self.value(Value::from_string(string_object.primitive_string()), depth + 1, false);
+ return;
+ }
+
+ self.append(object.class().class_name());
+ if object.is::<super::proxy_object::ProxyObject>() {
+ return;
+ }
+ if let Some(date) = object.downcast::<Date>() {
+ self.append(" ");
+ self.string(Utf16View::of_string(&to_date_string(date.date_value())), false);
+ return;
+ }
+
+ if depth >= MAX_DEPTH {
+ self.append(" {...}");
+ return;
+ }
+
+ if let Some(promise) = object.downcast::<Promise>() {
+ match promise.state() {
+ PromiseState::Pending => self.append(" {<pending>}"),
+ PromiseState::Fulfilled | PromiseState::Rejected => {
+ let state = if promise.state() == PromiseState::Fulfilled {
+ "fulfilled"
+ } else {
+ "rejected"
+ };
+ self.append(&format!(" {{<{state}>: "));
+ self.value(promise.result(), depth + 1, false);
+ self.append("}");
+ }
+ }
+ return;
+ }
+
+ if object.is::<Array>() {
+ self.append(" [");
+ let length = object.indexed_array_like_size();
+ for index in 0..length.min(MAX_ITEMS as u32) {
+ if self.full() {
+ break;
+ }
+ if index > 0 {
+ self.append(", ");
+ }
+ if let Some(entry) = object.indexed_get(index) {
+ self.value(entry.value, depth + 1, false);
+ } else {
+ self.append("<empty>");
+ }
+ }
+ if length > MAX_ITEMS as u32 {
+ self.append(", ...");
+ }
+ self.append("]");
+ return;
+ }
+
+ if let Some(map) = object.downcast::<Map>() {
+ self.append(" {");
+ let iterator = map.begin();
+ for index in 0..MAX_ITEMS {
+ if iterator.is_end() || self.full() {
+ break;
+ }
+ if index > 0 {
+ self.append(", ");
+ }
+ let entry = iterator.current();
+ self.value(entry.key, depth + 1, false);
+ self.append(" => ");
+ self.value(entry.value, depth + 1, false);
+ iterator.advance();
+ }
+ if !iterator.is_end() {
+ self.append(", ...");
+ }
+ self.append("}");
+ return;
+ }
+
+ if let Some(set) = object.downcast::<Set>() {
+ self.append(" {");
+ let iterator = set.begin();
+ for index in 0..MAX_ITEMS {
+ if iterator.is_end() || self.full() {
+ break;
+ }
+ if index > 0 {
+ self.append(", ");
+ }
+ self.value(iterator.current(), depth + 1, false);
+ iterator.advance();
+ }
+ if !iterator.is_end() {
+ self.append(", ...");
+ }
+ self.append("}");
+ return;
+ }
+
+ // An error leads with its message, so that the properties stored ahead of it can't push it past the item limit.
+ let message_key = &self.vm.names.message;
+ let is_error = object.is::<Error>();
+ let mut message_shown = false;
+ if is_error && let Some(metadata) = object.shape().lookup(message_key) {
+ let message = object.get_direct(metadata.offset);
+ if message.is_string() {
+ self.append(": ");
+ self.string(Utf16View::of_string(&message.as_string().utf16_string()), false);
+ message_shown = true;
+ }
+ }
+
+ self.append(" {");
+ let mut count = 0;
+ let indexed_length = object.indexed_array_like_size();
+ for index in 0..indexed_length.min(MAX_ITEMS as u32) {
+ if self.full() {
+ break;
+ }
+ if let Some(entry) = object.indexed_get(index) {
+ if count > 0 {
+ self.append(", ");
+ }
+ self.append(&format!("{index}: "));
+ self.value(entry.value, depth + 1, false);
+ count += 1;
+ }
+ }
+
+ // Keep the bounded set of preview keys on the stack, where the collector can see any symbol keys.
+ let remaining = MAX_ITEMS - count;
+ let mut properties = [const { None }; MAX_ITEMS];
+ let mut property_count = 0;
+ object.shape().for_each_property_in_insertion_order(|key, metadata| {
+ if property_count == remaining {
+ return ControlFlow::Break(());
+ }
+ if message_shown && key == message_key {
+ return ControlFlow::Continue(());
+ }
+ properties[property_count] = Some((key.clone(), metadata.offset));
+ property_count += 1;
+ ControlFlow::Continue(())
+ });
+ for (key, offset) in properties.iter().flatten() {
+ if self.full() {
+ break;
+ }
+ if count > 0 {
+ self.append(", ");
+ }
+ if key.is_symbol() {
+ self.value(Value::from_symbol(key.as_symbol()), depth + 1, false);
+ } else {
+ self.string(Utf16View::of_string(&key.to_utf16_string()), true);
+ }
+ self.append(": ");
+ self.value(object.get_direct(*offset), depth + 1, false);
+ count += 1;
+ }
+ if object.shape().property_count() as usize > property_count + usize::from(message_shown)
+ || indexed_length > MAX_ITEMS as u32
+ {
+ if count > 0 {
+ self.append(", ");
+ }
+ self.append("...");
+ }
+ self.append("}");
+ }
+}
+
+pub(super) fn format(vm: &Vm, value: Value, raw_strings: bool) -> String {
+ let mut preview = Preview {
+ vm,
+ text: String::new(),
+ truncated: false,
+ };
+ preview.value(value, 0, raw_strings);
+ if preview.full() {
+ preview.text.push_str("...");
+ }
+ preview.text
+}
diff --git a/Libraries/LibJS/Rust/src/runtime/mod.rs b/Libraries/LibJS/Rust/src/runtime/mod.rs
index 103421ad5c4..6a6729fd888 100644
--- a/Libraries/LibJS/Rust/src/runtime/mod.rs
+++ b/Libraries/LibJS/Rust/src/runtime/mod.rs
@@ -54,6 +54,7 @@ pub mod common_property_names;
pub mod completion;
pub mod console_object;
pub mod console_object_prototype;
+mod console_preview;
pub mod cyclic_module;
pub mod data_view;
pub mod data_view_constructor;
diff --git a/Libraries/LibJS/Rust/src/runtime/print.rs b/Libraries/LibJS/Rust/src/runtime/print.rs
index bbc5296ab5c..240eb5597c9 100644
--- a/Libraries/LibJS/Rust/src/runtime/print.rs
+++ b/Libraries/LibJS/Rust/src/runtime/print.rs
@@ -76,6 +76,7 @@ pub struct PrintContext<'a> {
pub stream: &'a mut dyn Write,
pub strip_ansi: bool,
pub raw_strings: bool,
+ pub compact: bool,
}
fn escape_for_string_literal(string: Utf16View<'_>) -> Vec<u16> {
@@ -1223,6 +1224,10 @@ fn print_value(
}
pub fn print(value: Value, print_context: &mut PrintContext<'_>) -> io::Result<()> {
+ if print_context.compact {
+ let preview = super::console_preview::format(print_context.vm, value, print_context.raw_strings);
+ return print_context.stream.write_all(preview.as_bytes());
+ }
let mut seen_objects = SeenObjects::new(print_context.vm);
print_value(print_context, value, &mut seen_objects)
}
diff --git a/Libraries/LibJS/Rust/src/utilities/js.rs b/Libraries/LibJS/Rust/src/utilities/js.rs
index 21767f7aeb8..290953b2ac6 100644
--- a/Libraries/LibJS/Rust/src/utilities/js.rs
+++ b/Libraries/LibJS/Rust/src/utilities/js.rs
@@ -1093,6 +1093,7 @@ fn print_inline(vm: &Vm, value: Value, stream: &mut dyn Write) -> io::Result<()>
stream,
strip_ansi: STRIP_ANSI.load(Ordering::Relaxed),
raw_strings: RAW_STRINGS.load(Ordering::Relaxed),
+ compact: false,
};
print(value, &mut print_context)
}
diff --git a/Libraries/LibWeb/HTML/Scripting/DevToolsLoggedObjects.cpp b/Libraries/LibWeb/HTML/Scripting/DevToolsLoggedObjects.cpp
index 8ddfaa6ace2..5ad0ede786d 100644
--- a/Libraries/LibWeb/HTML/Scripting/DevToolsLoggedObjects.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/DevToolsLoggedObjects.cpp
@@ -27,9 +27,12 @@ Vector<JsonValue> DevToolsLoggedObjects::serialize_message_arguments(ReadonlySpa
start_message();
Vector<JsonValue> serialized_arguments;
- serialized_arguments.ensure_capacity(arguments.size());
- for (auto argument : arguments)
+ auto preview_arguments = arguments.slice(0, min(arguments.size(), 100uz));
+ serialized_arguments.ensure_capacity(preview_arguments.size());
+ for (auto argument : preview_arguments)
serialized_arguments.unchecked_append(m_current_table.serialize_value_as_grip(argument));
+ if (preview_arguments.size() < arguments.size())
+ serialized_arguments.append("..."_string);
return serialized_arguments;
}
diff --git a/Libraries/LibWeb/HTML/Scripting/DevToolsObjectTable.cpp b/Libraries/LibWeb/HTML/Scripting/DevToolsObjectTable.cpp
index 9b1209adc78..b3dd2b86875 100644
--- a/Libraries/LibWeb/HTML/Scripting/DevToolsObjectTable.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/DevToolsObjectTable.cpp
@@ -5,6 +5,8 @@
*/
#include <AK/JsonArray.h>
+#include <AK/MemoryStream.h>
+#include <LibJS/Print.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/BigInt.h>
#include <LibJS/Runtime/Date.h>
@@ -35,6 +37,15 @@ static constexpr size_t PREVIEW_ITEM_COUNT = 10;
// one level deep: An array of elements shows each element's name, but an array of arrays shows only their lengths.
static constexpr u8 MAX_PREVIEW_DEPTH = 1;
+static String preview_text(Utf16View text)
+{
+ constexpr size_t limit = 1024;
+ auto prefix = text.substring_view(0, min(text.length_in_code_units(), limit)).to_utf8_but_should_be_ported_to_utf16();
+ if (text.length_in_code_units() > limit)
+ return MUST(String::formatted("{}...", prefix));
+ return prefix;
+}
+
WebView::DebuggerValue DevToolsObjectTable::serialize_value(JS::Value value)
{
return serialize_value(value, 0);
@@ -140,6 +151,20 @@ WebView::DebuggerValue DevToolsObjectTable::serialize_value(JS::Value value, u8
// object actor.
JsonValue DevToolsObjectTable::grip_value(JS::Value value, u8 depth)
{
+ if (value.is_bigint() || value.is_symbol()) {
+ auto& vm = value.is_bigint() ? value.as_bigint().vm() : value.as_symbol().vm();
+ AllocatingMemoryStream stream;
+ JS::PrintContext context { .vm = vm, .stream = &stream, .strip_ansi = true, .compact = true };
+ MUST(JS::print(value, context));
+ auto text = MUST(String::from_stream(stream, stream.used_buffer_size()));
+ if (value.is_symbol())
+ return text;
+ JsonObject grip;
+ grip.set("type"sv, "BigInt"sv);
+ grip.set("text"sv, move(text));
+ return grip;
+ }
+
auto serialized = serialize_value(value, depth);
JsonObject grip;
@@ -168,7 +193,7 @@ JsonValue DevToolsObjectTable::grip_value(JS::Value value, u8 depth)
}
return serialized.number_value;
case WebView::DebuggerValueType::String:
- return serialized.text.to_utf8();
+ return preview_text(serialized.text);
case WebView::DebuggerValueType::BigInt:
grip.set("type"sv, "BigInt"sv);
grip.set("text"sv, serialized.text.to_utf8());
@@ -248,7 +273,7 @@ JsonObject DevToolsObjectTable::grip_fields_for_object(JS::Object& object, u8 de
preview.set("nodeType"sv, node->node_type());
preview.set("isConnected"sv, node->is_connected());
- auto node_name = node->node_name().view().to_utf8_but_should_be_ported_to_utf16();
+ auto node_name = preview_text(node->node_name().view());
if (auto const* element = as_if<DOM::Element>(*node)) {
// The nodeName of an HTML element is its tag name in uppercase, but a console writes the tag the way the
// markup does.
@@ -256,13 +281,13 @@ JsonObject DevToolsObjectTable::grip_fields_for_object(JS::Object& object, u8 de
node_name = node_name.to_ascii_lowercase();
JsonObject attributes;
- element->for_each_attribute([&](Utf16FlyString name, Utf16String value) {
- attributes.set(name.view().to_utf8_but_should_be_ported_to_utf16(), value.to_utf8());
- });
+ for (auto const& attribute : element->attribute_list().slice(0, min(element->attribute_list_size(), PREVIEW_ITEM_COUNT))) {
+ attributes.set(preview_text(attribute.name.as_string().view()), preview_text(attribute.value));
+ }
preview.set("attributes"sv, move(attributes));
preview.set("attributesLength"sv, element->attribute_list_size());
} else if (auto const* character_data = as_if<DOM::CharacterData>(*node)) {
- preview.set("textContent"sv, character_data->data().to_utf8());
+ preview.set("textContent"sv, preview_text(character_data->data()));
} else if (auto const* document = as_if<DOM::Document>(*node)) {
preview.set("location"sv, document->url().serialize());
}
@@ -331,7 +356,7 @@ JsonObject DevToolsObjectTable::grip_fields_for_object(JS::Object& object, u8 de
if (object.is_function()) {
auto name = read_property_without_running_script(object, "name"sv);
if (name.has_value() && name->is_string()) {
- auto function_name = name->as_string().utf16_string().to_utf8();
+ auto function_name = preview_text(name->as_string().utf16_string_view());
fields.set("name"sv, function_name);
fields.set("displayName"sv, move(function_name));
}
@@ -345,7 +370,7 @@ JsonObject DevToolsObjectTable::grip_fields_for_object(JS::Object& object, u8 de
}
if (auto* regexp = as_if<JS::RegExpObject>(object)) {
- fields.set("displayString"sv, MUST(String::formatted("/{}/{}", regexp->pattern(), regexp->flags())));
+ fields.set("displayString"sv, MUST(String::formatted("/{}/{}", preview_text(regexp->pattern()), regexp->flags())));
return fields;
}
@@ -368,12 +393,14 @@ JsonObject DevToolsObjectTable::grip_fields_for_object(JS::Object& object, u8 de
JsonObject own_properties;
size_t own_properties_length = 0;
+ size_t previewed_properties = 0;
for (auto const& key : keys.value()) {
if (!key.is_string())
continue;
++own_properties_length;
- if (!lists_contents || own_properties.size() >= PREVIEW_ITEM_COUNT)
+ if (!lists_contents || previewed_properties >= PREVIEW_ITEM_COUNT)
continue;
+ ++previewed_properties;
auto name = key.as_string().utf16_string();
auto descriptor = object.internal_get_own_property(JS::PropertyKey { name });
@@ -391,7 +418,7 @@ JsonObject DevToolsObjectTable::grip_fields_for_object(JS::Object& object, u8 de
}
serialized.set("configurable"sv, property.configurable.value_or(false));
serialized.set("enumerable"sv, property.enumerable.value_or(false));
- own_properties.set(name.to_utf8(), move(serialized));
+ own_properties.set(preview_text(name), move(serialized));
}
preview.set("kind"sv, "Object"sv);
diff --git a/Services/WebContent/DevToolsConsoleClient.cpp b/Services/WebContent/DevToolsConsoleClient.cpp
index a8838a30e80..a637386908c 100644
--- a/Services/WebContent/DevToolsConsoleClient.cpp
+++ b/Services/WebContent/DevToolsConsoleClient.cpp
@@ -8,11 +8,15 @@
#include <AK/JsonObject.h>
#include <AK/JsonValue.h>
#include <AK/MemoryStream.h>
+#include <AK/StringBuilder.h>
+#include <AK/Utf16StringBuilder.h>
#include <LibGC/Heap.h>
#include <LibJS/Print.h>
#include <LibJS/Runtime/BigInt.h>
#include <LibJS/Runtime/ErrorData.h>
#include <LibJS/Runtime/Realm.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/DOM/Element.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/Window.h>
@@ -40,11 +44,35 @@ DevToolsConsoleClient::DevToolsConsoleClient(JS::Console& console, PageClient& c
DevToolsConsoleClient::~DevToolsConsoleClient() = default;
+static String console_text(JS::Realm& realm, JS::Value value)
+{
+ if (value.is_object()) {
+ if (auto const* element = Web::Bindings::impl_from<Web::DOM::Element>(&value.as_object())) {
+ StringBuilder builder;
+ builder.append('<');
+ auto name = element->local_name().view();
+ builder.append(name.substring_view(0, min(name.length_in_code_units(), 256uz)).to_utf8_but_should_be_ported_to_utf16());
+ if (element->id().has_value()) {
+ auto id = element->id()->view();
+ builder.append(" id=\""sv);
+ builder.append(id.substring_view(0, min(id.length_in_code_units(), 256uz)).to_utf8_but_should_be_ported_to_utf16());
+ builder.append('"');
+ }
+ builder.append('>');
+ return MUST(builder.to_string());
+ }
+ }
+
+ Web::HTML::TemporaryExecutionContext execution_context { realm };
+ AllocatingMemoryStream stream;
+ JS::PrintContext context { .vm = realm.vm(), .stream = &stream, .strip_ansi = true, .compact = true };
+ MUST(JS::print(value, context));
+ return MUST(String::from_stream(stream, stream.used_buffer_size()));
+}
+
// https://firefox-source-docs.mozilla.org/devtools/backend/protocol.html#grips
JsonValue DevToolsConsoleClient::serialize_value(JS::Realm& realm, JS::Value value)
{
- auto& vm = realm.vm();
-
auto serialize_type = [](StringView type) {
JsonObject serialized;
serialized.set("type"sv, type);
@@ -60,8 +88,13 @@ JsonValue DevToolsConsoleClient::serialize_value(JS::Realm& realm, JS::Value val
if (value.is_boolean())
return value.as_bool();
- if (value.is_string())
- return value.as_string().utf16_string_view().to_utf8_but_should_be_ported_to_utf16();
+ if (value.is_string()) {
+ auto text = value.as_string().utf16_string_view();
+ auto prefix = text.substring_view(0, min(text.length_in_code_units(), 1024uz)).to_utf8_but_should_be_ported_to_utf16();
+ if (text.length_in_code_units() > 1024)
+ return MUST(String::formatted("{}...", prefix));
+ return prefix;
+ }
if (value.is_number()) {
if (value.is_nan())
@@ -77,23 +110,16 @@ JsonValue DevToolsConsoleClient::serialize_value(JS::Realm& realm, JS::Value val
if (value.is_bigint()) {
auto serialized = serialize_type("BigInt"sv);
- serialized.set("text"sv, MUST(value.as_bigint().big_integer().to_base(10)));
+ auto text = console_text(realm, value);
+ serialized.set("text"sv, text.ends_with('n') ? MUST(text.substring_from_byte_offset(0, text.bytes_as_string_view().length() - 1)) : text);
return serialized;
}
if (value.is_symbol())
- return value.as_symbol().descriptive_string().to_utf8();
+ return console_text(realm, value);
- // FIXME: Handle serialization of object grips. For now, we stringify the object.
- if (value.is_object()) {
- Web::HTML::TemporaryExecutionContext execution_context { realm };
- AllocatingMemoryStream stream;
-
- JS::PrintContext context { .vm = vm, .stream = &stream, .strip_ansi = true };
- MUST(JS::print(value, context));
-
- return MUST(String::from_stream(stream, stream.used_buffer_size()));
- }
+ if (value.is_object())
+ return console_text(realm, value);
return {};
}
@@ -231,7 +257,31 @@ JS::ThrowCompletionOr<JS::Value> DevToolsConsoleClient::printer(JS::Console::Log
auto const& argument_values = arguments.get<GC::RootVector<JS::Value>>();
- auto output = TRY(generically_format_values(argument_values));
+ Vector<JsonValue> printed_arguments;
+ Utf16StringBuilder output_builder;
+ auto argument_count = min(argument_values.size(), 100uz);
+ for (size_t index = 0; index < argument_count; ++index) {
+ if (output_builder.length_in_code_units() >= 8192) {
+ output_builder.append_ascii(" ..."sv);
+ printed_arguments.append("..."_string);
+ break;
+ }
+ auto value = argument_values[index];
+ auto serialized = serialize_value(m_console->realm(), value);
+ auto text = value.is_object() ? serialized.as_string() : console_text(m_console->realm(), value);
+ if (index > 0)
+ output_builder.append_ascii(' ');
+ auto utf16_text = Utf16String::from_utf8(text);
+ auto remaining = 8192 - output_builder.length_in_code_units();
+ output_builder.append(utf16_text.utf16_view().substring_view(0, min(utf16_text.length_in_code_units(), remaining)));
+ printed_arguments.append(move(serialized));
+ if (utf16_text.length_in_code_units() > remaining || (index + 1 == argument_count && argument_count < argument_values.size())) {
+ output_builder.append_ascii(" ..."sv);
+ printed_arguments.append("..."_string);
+ break;
+ }
+ }
+ auto output = output_builder.to_string();
m_console->output_debug_message(log_level, output);
auto timestamp = UnixDateTime::now();
@@ -252,13 +302,9 @@ JS::ThrowCompletionOr<JS::Value> DevToolsConsoleClient::printer(JS::Console::Log
auto is_table = log_level == JS::Console::LogLevel::Table && !argument_values.is_empty() && argument_values.first().is_object();
// The buffer keeps the arguments printed, so it keeps no objects alive, and a table as its text.
- Vector<JsonValue> printed_arguments;
if (is_table) {
+ printed_arguments.clear();
printed_arguments.append(output.to_utf8());
- } else {
- printed_arguments.ensure_capacity(argument_values.size());
- for (auto value : argument_values)
- printed_arguments.unchecked_append(serialize_value(m_console->realm(), value));
}
m_client->buffer_console_output(console_log(is_table ? JS::Console::LogLevel::Log : log_level, printed_arguments));
diff --git a/Tests/LibJS/Bytecode/expected/for-loop-scoping.txt b/Tests/LibJS/Bytecode/expected/for-loop-scoping.txt
index 965c27ba264..d4117ca1d5d 100644
--- a/Tests/LibJS/Bytecode/expected/for-loop-scoping.txt
+++ b/Tests/LibJS/Bytecode/expected/for-loop-scoping.txt
@@ -134,4 +134,4 @@ block0:
[ 20] Return value:reg5
-[ 0, 1, 2 ]
+Array [0, 1, 2]
diff --git a/Tests/LibJS/Bytecode/expected/object-destructuring-rebinds-source-variable.txt b/Tests/LibJS/Bytecode/expected/object-destructuring-rebinds-source-variable.txt
index dd8ba2ae5e8..d7456aeca75 100644
--- a/Tests/LibJS/Bytecode/expected/object-destructuring-rebinds-source-variable.txt
+++ b/Tests/LibJS/Bytecode/expected/object-destructuring-rebinds-source-variable.txt
@@ -43,4 +43,4 @@ block0:
[ a8] Return value:reg5
-[ 1, 2, 3 ]
+Array [1, 2, 3]
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 26469a2ea80..46b321f9dfc 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -3,6 +3,7 @@ Layout/input/pdf-viewer.pdf
Text/input/PDF/jbig2-image.html
[LoadFromHttpServer]
+Text/input/wpt-import/console/console-log-large-array.any.worker.html
; A data: iframe stays in this process only under an http: page.
Text/input/HTML/cross-origin-rejected-promise-realm.html
Text/input/HTML/cross-origin-receiver-security-check.html
diff --git a/Tests/LibWeb/Text/expected/wpt-import/console/console-log-large-array.any.txt b/Tests/LibWeb/Text/expected/wpt-import/console/console-log-large-array.any.txt
new file mode 100644
index 00000000000..6e1c2643731
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/console/console-log-large-array.any.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Logging large arrays works
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/console/console-log-large-array.any.worker.txt b/Tests/LibWeb/Text/expected/wpt-import/console/console-log-large-array.any.worker.txt
new file mode 100644
index 00000000000..6e1c2643731
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/console/console-log-large-array.any.worker.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Logging large arrays works
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/wpt-import/console/console-log-large-array.any.html b/Tests/LibWeb/Text/input/wpt-import/console/console-log-large-array.any.html
new file mode 100644
index 00000000000..c4dcdf27dc1
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/console/console-log-large-array.any.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<meta charset=utf-8>
+
+<script>
+self.GLOBAL = {
+ isWindow: function() { return true; },
+ isWorker: function() { return false; },
+ isShadowRealm: function() { return false; },
+};
+</script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+
+<div id=log></div>
+<script src="../console/console-log-large-array.any.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/console/console-log-large-array.any.js b/Tests/LibWeb/Text/input/wpt-import/console/console-log-large-array.any.js
new file mode 100644
index 00000000000..b3576b2d949
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/console/console-log-large-array.any.js
@@ -0,0 +1,8 @@
+// META: global=window,dedicatedworker
+"use strict";
+// https://console.spec.whatwg.org/
+
+test(() => {
+ console.log(new Array(10000000).fill("x"));
+ console.log(new Uint8Array(10000000));
+}, "Logging large arrays works");
diff --git a/Tests/LibWeb/Text/input/wpt-import/console/console-log-large-array.any.worker.html b/Tests/LibWeb/Text/input/wpt-import/console/console-log-large-array.any.worker.html
new file mode 100644
index 00000000000..46f02ae1b2d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/console/console-log-large-array.any.worker.html
@@ -0,0 +1,9 @@
+<!doctype html>
+<meta charset=utf-8>
+
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<div id=log></div>
+<script>
+fetch_tests_from_worker(new Worker("../console/console-log-large-array.any.worker.js"));
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/console/console-log-large-array.any.worker.js b/Tests/LibWeb/Text/input/wpt-import/console/console-log-large-array.any.worker.js
new file mode 100644
index 00000000000..f0c668cf615
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/console/console-log-large-array.any.worker.js
@@ -0,0 +1,10 @@
+
+self.GLOBAL = {
+ isWindow: function() { return false; },
+ isWorker: function() { return true; },
+ isShadowRealm: function() { return false; },
+};
+importScripts("/resources/testharness.js");
+
+importScripts("/console/console-log-large-array.any.js");
+done();
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index e2c384e284e..1d276e28329 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -3,6 +3,7 @@ if (BUILD_TESTING AND NOT WIN32)
ladybird_python_test(test-devtools-catch-up-layout.py ARGS $<TARGET_FILE:ladybird>)
ladybird_python_test(test-devtools-client-follows-the-tab.py ARGS $<TARGET_FILE:ladybird>)
ladybird_python_test(test-iframe-console.py ARGS $<TARGET_FILE:ladybird>)
+ ladybird_python_test(test-console-previews.py ARGS $<TARGET_FILE:ladybird>)
ladybird_python_test(test-message-port-collection.py ARGS $<TARGET_FILE:WebDriver>)
ladybird_python_test(test-shared-stylesheet-memory.py ARGS $<TARGET_FILE:WebDriver> TIMEOUT 180)
ladybird_python_test(test-user-agent-preset-reaches-child-frames.py ARGS $<TARGET_FILE:ladybird>)
diff --git a/Tests/LibWebView/test-console-previews.py b/Tests/LibWebView/test-console-previews.py
new file mode 100755
index 00000000000..6a3b931c212
--- /dev/null
+++ b/Tests/LibWebView/test-console-previews.py
@@ -0,0 +1,182 @@
+#!/usr/bin/env python3
+#
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+import argparse
+import http.server
+import runpy
+import tempfile
+import threading
+
+from pathlib import Path
+
+devtools = runpy.run_path(str(Path(__file__).with_name("test-devtools-client-follows-the-tab.py")))
+PAGE = b"""<!doctype html><title>console-previews</title><dfn id="definition">Definition</dfn>
+<script>
+window.getterCalls = 0;
+const inherited = { get inherited() { ++getterCalls; return 1; } };
+const object = Object.create(inherited, {
+ own: { enumerable: true, get() { ++getterCalls; return 2; } },
+});
+console.log("before watching", object);
+window.loaded = true;
+</script>"""
+WORKER = b"""
+let calls = 0;
+const object = Object.create({ get inherited() { ++calls; return 1; } }, {
+ own: { enumerable: true, get() { ++calls; return 2; } },
+});
+console.log(object);
+console.log(new Array(0xffffffff));
+postMessage(calls);
+"""
+
+
+class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(200)
+ self.send_header("Content-Type", "text/javascript" if self.path == "/worker.js" else "text/html")
+ self.end_headers()
+ self.wfile.write(WORKER if self.path == "/worker.js" else PAGE)
+
+ def log_message(self, format, *args):
+ pass
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("ladybird_binary")
+ binary = parser.parse_args().ladybird_binary
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ url = f"http://127.0.0.1:{server.server_port}/page"
+ try:
+ with tempfile.TemporaryDirectory(prefix="ladybird-console-previews-") as profile:
+ process, _, client = devtools["launch"](binary, profile, url)
+ try:
+ devtools["wait_for_page"](client, url, "console-previews")
+ watcher = client.watch_frame_targets()
+ devtools["wait_until"]("the page has logged", lambda: client.evaluate("window.loaded === true"))
+ calls = client.evaluate("window.getterCalls")
+ assert calls == 0, f"Logging invoked getters {calls} times"
+ client.evaluate("""(() => {
+ const worker = new Worker('/worker.js');
+ worker.onmessage = event => { window.workerCalls = event.data; worker.terminate(); };
+ worker.onerror = () => { window.workerCalls = 'error'; };
+ })()""")
+ devtools["wait_until"]("the worker has logged", lambda: client.evaluate("'workerCalls' in window"))
+ assert client.evaluate("window.workerCalls") == 0, "Worker logging invoked getters or failed"
+
+ messages = []
+ receive = client.receive
+
+ def receive_and_record():
+ packet = receive()
+ if packet.get("type") == "resources-available-array":
+ for resource_type, resources in packet.get("array", []):
+ if resource_type == "console-message":
+ messages.extend(resources)
+ return packet
+
+ client.receive = receive_and_record
+
+ def logged(label):
+ return next((m for m in messages if m["arguments"][0] == label), None)
+
+ def message_arguments(label):
+ message = logged(label)
+ assert message is not None, label
+ return message["arguments"]
+
+ # These messages must be bounded before a client subscribes, as well as when it is watching.
+ client.evaluate("""(() => {
+ const cycle = {}; cycle.self = cycle;
+ console.log('cycle', cycle);
+ console.log('large string', 'x'.repeat(1000000));
+ console.log('large array', Array(100000).fill('x'.repeat(1000)));
+ console.log('sparse array', new Array(0xffffffff));
+ console.log('large map', new Map(Array.from({ length: 10000 }, (_, i) => [i, 'x'.repeat(1000)])));
+ console.log('large set', new Set(Array.from({ length: 10000 }, (_, i) => i)));
+ const array = [];
+ Object.defineProperty(array, 0, { get() { ++getterCalls; return 1; } });
+ console.log('array getter', array);
+ let deep = {};
+ for (let i = 0; i < 10000; ++i) deep = { next: deep };
+ console.log('deep object', deep);
+ console.log('large symbol', Symbol('x'.repeat(1000000)));
+ console.log('large bigint', 1n << 1000000n);
+ console.log('many arguments', ...Array(200).fill('x'.repeat(1000)));
+ console.log('many small arguments', ...Array(200).fill('x'));
+ console.log('buffered DOM', document.getElementById('definition'));
+ window.traps = 0;
+ const handler = {};
+ for (const name of ['get', 'getPrototypeOf', 'ownKeys', 'getOwnPropertyDescriptor'])
+ handler[name] = () => { ++traps; throw Error(name); };
+ console.log('proxy', new Proxy({}, handler));
+ return traps;
+ })()""")
+ assert client.evaluate("window.traps") == 0, "Logging invoked a proxy trap"
+ client.send({"to": watcher, "type": "watchResources", "resourceTypes": ["console-message"]})
+ client.receive_matching(lambda packet: logged("proxy") is not None)
+ for label in [
+ "cycle",
+ "large string",
+ "large array",
+ "sparse array",
+ "large map",
+ "large set",
+ "deep object",
+ "large symbol",
+ "buffered DOM",
+ ]:
+ message = logged(label)
+ assert message is not None, label
+ preview = message["arguments"][1]
+ assert isinstance(preview, str) and len(preview) < 16384, (label, type(preview))
+ assert preview, label
+
+ assert "Getter" in message_arguments("before watching")[1]
+ assert "inherited" not in message_arguments("before watching")[1]
+ assert message_arguments("buffered DOM")[1] == '<dfn id="definition">'
+ assert len(message_arguments("large bigint")[1]["text"]) < 16384
+ assert sum(len(value) for value in message_arguments("many arguments")) < 16384
+ assert message_arguments("many arguments")[-1] == "..."
+ assert message_arguments("many small arguments")[-1] == "..."
+
+ client.evaluate("console.log('after watching', object); undefined")
+ assert client.evaluate("window.getterCalls") == 0, "A live preview invoked a getter"
+ client.evaluate("""(() => {
+ const element = document.getElementById('definition');
+ for (let i = 0; i < 20; ++i) element.setAttribute('data-' + i, 'x'.repeat(100000));
+ Object.defineProperty(element, 'innerText', { get() { ++getterCalls; return 'unexpected'; } });
+ console.log('DOM element', element);
+ console.log('live string', 'x'.repeat(1000000));
+ })()""")
+ if logged("DOM element") is None:
+ client.receive_matching(lambda packet: logged("DOM element") is not None)
+ grip = message_arguments("DOM element")[1]
+ assert grip["preview"]["kind"] == "DOMNode", grip
+ assert grip["preview"]["nodeName"] == "dfn", grip
+ assert len(grip["preview"]["attributes"]) <= 10, grip
+ assert all(len(value) < 2048 for value in grip["preview"]["attributes"].values()), grip
+ if logged("live string") is None:
+ client.receive_matching(lambda packet: logged("live string") is not None)
+ assert len(message_arguments("live string")[1]) < 16384
+ assert client.evaluate("window.getterCalls") == 0, "A DOM preview invoked a getter"
+ actor = grip["actor"]
+ client.send({"to": actor, "type": "prototypeAndProperties"})
+ properties = client.receive_matching(lambda packet: packet.get("from") == actor)
+ assert "ownProperties" in properties, properties
+ print("PASS: Console previews are bounded, avoid getters and proxy traps, and DOM objects expand")
+ finally:
+ client.close()
+ devtools["stop"](process)
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+if __name__ == "__main__":
+ main()