Truly independent web browser
LibWeb: Follow the WebIDL observable array traps in ObservableArray
Andreas Kling06ca30282137
diff --git a/Libraries/LibWeb/DOM/AdoptedStyleSheets.cpp b/Libraries/LibWeb/DOM/AdoptedStyleSheets.cppindex 6545a9505e8..3d04cae1953 100644--- a/Libraries/LibWeb/DOM/AdoptedStyleSheets.cpp+++ b/Libraries/LibWeb/DOM/AdoptedStyleSheets.cpp@@ -23,16 +23,47 @@ GC::Ref<WebIDL::ObservableArray> AdoptedStyleSheetsAccess::adopted_style_sheets(return shadow_root.adopted_style_sheets();}+// NB: The engine holds each sheet once. A sheet that the array holds more than once is placed at its last occurrence,+// where its rules win the cascade.+static Optional<u32> last_index_of(WebIDL::ObservableArray& adopted_style_sheets, CSS::StyleSheetState& style_sheet, u32 skipped_index)+{+ for (auto index = adopted_style_sheets.length(); index > 0;) {+ --index;+ if (index == skipped_index)+ continue;+ if (auto value = adopted_style_sheets.element_value(index); value.has_value() && CSS::css_style_sheet_from_value(*value) == &style_sheet)+ return index;+ }+ return {};+}++// The first sheet after index that the engine places there, which is one that does not occur again later.+static CSS::StyleSheetState* first_sheet_after(WebIDL::ObservableArray& adopted_style_sheets, u32 index, u32 skipped_index)+{+ for (auto next_index = index + 1; next_index < adopted_style_sheets.length(); ++next_index) {+ if (next_index == skipped_index)+ continue;+ if (auto value = adopted_style_sheets.element_value(next_index); value.has_value()) {+ auto* style_sheet = CSS::css_style_sheet_from_value(*value);+ if (style_sheet && last_index_of(adopted_style_sheets, *style_sheet, skipped_index) == next_index)+ return style_sheet;+ }+ }+ return nullptr;+}+GC::Ref<WebIDL::ObservableArray> create_adopted_style_sheets_list(Node& document_or_shadow_root){auto& realm = document_or_shadow_root.document().relevant_settings_object().realm();auto adopted_style_sheets = WebIDL::ObservableArray::create(realm);- adopted_style_sheets->set_on_set_an_indexed_value_callback(GC::create_function(realm.heap(), GC::captures(document_or_shadow_root, adopted_style_sheets), [](Node& document_or_shadow_root, GC::Ref<WebIDL::ObservableArray>& adopted_style_sheets, u32 index, JS::Value& value) -> WebIDL::ExceptionOr<void> {- auto& vm = document_or_shadow_root.vm();+ adopted_style_sheets->set_convert_to_idl_value_callback(GC::create_function(realm.heap(), GC::captures(document_or_shadow_root), [](Node& document_or_shadow_root, JS::Value value) -> WebIDL::ExceptionOr<void> {auto style_sheet = CSS::css_style_sheet_from_value(value);if (!style_sheet)- return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "CSSStyleSheet");+ return document_or_shadow_root.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "CSSStyleSheet");+ // NB: These are the steps of the set an indexed value algorithm, which runs after the delete algorithm for+ // the value it replaces. That delete algorithm has no effect that script can observe, so checking first+ // is not observable either, and keeps a rejected replacement from detaching the sheet that stays.// The set an indexed value algorithm for adoptedStyleSheets, given value and index, is the following:// 1. If value’s constructed flag is not set, or its constructor document is not equal to this// DocumentOrShadowRoot's node document, throw a "NotAllowedError" DOMException.@@ -40,23 +71,41 @@ GC::Ref<WebIDL::ObservableArray> create_adopted_style_sheets_list(Node& documentreturn WebIDL::NotAllowedError::create("StyleSheet's constructed flag is not set."_utf16);if (!style_sheet->constructed() || style_sheet->constructor_document().ptr() != &document_or_shadow_root.document())return WebIDL::NotAllowedError::create("Sharing a StyleSheet between documents is not allowed."_utf16);+ return {};+ }));+ adopted_style_sheets->set_on_set_an_indexed_value_callback(GC::create_function(realm.heap(), GC::captures(document_or_shadow_root, adopted_style_sheets), [](Node& document_or_shadow_root, GC::Ref<WebIDL::ObservableArray>& adopted_style_sheets, u32 index, JS::Value& value) -> WebIDL::ExceptionOr<void> {+ auto style_sheet = CSS::css_style_sheet_from_value(value);+ VERIFY(style_sheet);// Adopted sheets are not in any StyleSheetList, so nothing else announces them to the// engine. Observable array operations can write displaced entries before the insertion// point, so preserve their final order by attaching before the entry currently following// this index.- CSS::StyleSheetState* before = nullptr;- if (auto successor = adopted_style_sheets->element_value(index + 1); successor.has_value())- before = CSS::css_style_sheet_from_value(*successor);- CSS::record_stylesheet_attached(*style_sheet, document_or_shadow_root, before);+ if (auto last_index = last_index_of(adopted_style_sheets, *style_sheet, index); last_index.has_value() && *last_index > index)+ return {};+ CSS::record_stylesheet_attached(*style_sheet, document_or_shadow_root, first_sheet_after(adopted_style_sheets, index, index));CSS::Invalidation::invalidate_style_after_adopting_style_sheet(document_or_shadow_root, *style_sheet);return {};}));- adopted_style_sheets->set_on_delete_an_indexed_value_callback(GC::create_function(realm.heap(), GC::captures(document_or_shadow_root), [](Node& document_or_shadow_root, JS::Value value) -> WebIDL::ExceptionOr<void> {+ adopted_style_sheets->set_on_delete_an_indexed_value_callback(GC::create_function(realm.heap(), GC::captures(document_or_shadow_root, adopted_style_sheets), [](Node& document_or_shadow_root, GC::Ref<WebIDL::ObservableArray>& adopted_style_sheets, JS::Value value, u32 index) -> WebIDL::ExceptionOr<void> {+ // NB: Object.defineProperty() bypasses the set callback, so script can put any value in the array, including a+ // sheet that the list could not have adopted, such as the sheet of a style element. Its attachment is not+ // the list's to change.auto* style_sheet = CSS::css_style_sheet_from_value(value);- VERIFY(style_sheet);- CSS::record_stylesheet_detached(*style_sheet, document_or_shadow_root);- CSS::Invalidation::invalidate_style_after_removing_adopted_style_sheet(document_or_shadow_root, *style_sheet);+ if (!style_sheet || !style_sheet->constructed() || style_sheet->constructor_document().ptr() != &document_or_shadow_root.document())+ return {};++ // NB: The deleted value is still at index.+ auto last_index = last_index_of(adopted_style_sheets, *style_sheet, index);+ if (!last_index.has_value()) {+ CSS::record_stylesheet_detached(*style_sheet, document_or_shadow_root);+ CSS::Invalidation::invalidate_style_after_removing_adopted_style_sheet(document_or_shadow_root, *style_sheet);+ return {};+ }+ if (*last_index > index)+ return {};+ CSS::record_stylesheet_attached(*style_sheet, document_or_shadow_root, first_sheet_after(adopted_style_sheets, *last_index, index));+ CSS::Invalidation::invalidate_style_after_adopting_style_sheet(document_or_shadow_root, *style_sheet);return {};}));diff --git a/Libraries/LibWeb/WebIDL/ObservableArray.cpp b/Libraries/LibWeb/WebIDL/ObservableArray.cppindex 00fb4806b4e..908040eec52 100644--- a/Libraries/LibWeb/WebIDL/ObservableArray.cpp+++ b/Libraries/LibWeb/WebIDL/ObservableArray.cpp@@ -24,19 +24,173 @@ struct ObservableArrayHostClassTraits {return *observable_array;}+ // NB: Object.defineProperty() and Object.preventExtensions() bypass these hooks, so the array can refuse a store that+ // the spec never refuses. This checks for that before any callback runs.+ static bool can_store(JS::HostArray& array, JS::PropertyKey const& property_key)+ {+ auto descriptor = MUST(array.internal_get_own_property(property_key));+ if (!descriptor.has_value())+ return array.extensible();+ return descriptor->is_data_descriptor() && descriptor->writable.value_or(false);+ }++ static bool can_remove(JS::HostArray& array, u32 index)+ {+ auto descriptor = MUST(array.internal_get_own_property(index));+ return !descriptor.has_value() || descriptor->configurable.value_or(false);+ }++ // https://webidl.spec.whatwg.org/#js-observable-array-setstatic JS::ThrowCompletionOr<bool> set(JS::HostArray& array, JS::PropertyKey const& property_key, JS::Value value, JS::Value receiver, JS::CacheableSetPropertyMetadata* metadata, JS::Object::PropertyLookupPhase phase){+ auto& vm = array.vm();++ // 2. If P is "length", then return the result of setting the length given handler and V.+ if (property_key == vm.names.length)+ return set_the_length(array, value);++ // 3. If P is an array index, then return the result of setting the indexed value given handler, P, and V.if (property_key.is_number())- TRY(observable_array_of(array).run_set_an_indexed_value_callback(property_key.as_number(), value));+ return set_the_indexed_value(array, property_key.as_number(), value);++ // 4. Return ? O.[[Set]](P, V, Receiver).return array.array_set(property_key, value, receiver, metadata, phase);}+ // https://webidl.spec.whatwg.org/#js-observable-array-deletePropertystatic JS::ThrowCompletionOr<bool> delete_property(JS::HostArray& array, JS::PropertyKey const& property_key){- if (property_key.is_number())- TRY(observable_array_of(array).run_delete_an_indexed_value_callback(property_key.as_number()));+ auto& vm = array.vm();+ auto& observable_array = observable_array_of(array);++ // 2. If P is "length", then return false.+ if (property_key == vm.names.length)+ return false;++ // 3. If P is an array index, then:+ if (property_key.is_number()) {+ // 1. Let oldLen be handler.[[BackingList]]'s size.+ auto old_length = observable_array.length();++ // 2. Let index be ! ToUint32(P).+ auto index = property_key.as_number();++ // 3. If index ≠ oldLen − 1, then return false.+ if (old_length == 0 || index != old_length - 1)+ return false;++ if (!can_store(array, vm.names.length) || !can_remove(array, index))+ return false;++ // 4. Perform the algorithm steps given by handler.[[DeleteAlgorithm]], given handler.[[BackingList]][index]+ // and index.+ TRY(observable_array.run_delete_an_indexed_value_callback(index));++ // 5. Remove the last item from handler.[[BackingList]].+ // 6. Return true.+ return array.array_set(vm.names.length, JS::Value(index), &array);+ }++ // 4. Return ? O.[[Delete]](P).return array.array_delete(property_key);}++ // https://webidl.spec.whatwg.org/#observable-array-exotic-object-set-the-length+ static JS::ThrowCompletionOr<bool> set_the_length(JS::HostArray& array, JS::Value new_length)+ {+ auto& vm = array.vm();+ auto& observable_array = observable_array_of(array);++ // 1. Let uint32Len be ? ToUint32(newLen).+ auto uint32_length = TRY(new_length.to_u32(vm));++ // 2. Let numberLen be ? ToNumber(newLen).+ auto number_length = TRY(new_length.to_double(vm));++ // 3. If uint32Len ≠ numberLen, then throw a RangeError exception.+ if (uint32_length != number_length)+ return vm.throw_completion<JS::RangeError>(JS::ErrorType::InvalidLength, "array");++ // 4. Let oldLen be handler.[[BackingList]]'s size.+ auto old_length = observable_array.length();++ // 5. If uint32Len > oldLen, then return false.+ if (uint32_length > old_length)+ return false;++ if (!can_store(array, vm.names.length))+ return false;++ // 6. Let indexToDelete be oldLen − 1.+ // 7. While indexToDelete ≥ uint32Len:+ for (auto index_to_delete = old_length; index_to_delete > uint32_length;) {+ --index_to_delete;++ if (!can_remove(array, index_to_delete))+ return false;++ // 1. Perform the algorithm steps given by handler.[[DeleteAlgorithm]], given+ // handler.[[BackingList]][indexToDelete] and indexToDelete.+ TRY(observable_array.run_delete_an_indexed_value_callback(index_to_delete));++ // 2. Remove the last item from handler.[[BackingList]].+ if (!TRY(array.array_set(vm.names.length, JS::Value(index_to_delete), &array)))+ return false;++ // 3. Set indexToDelete to indexToDelete − 1.+ }++ // 8. Return true.+ return true;+ }++ // https://webidl.spec.whatwg.org/#observable-array-exotic-object-set-the-indexed-value+ static JS::ThrowCompletionOr<bool> set_the_indexed_value(JS::HostArray& array, u32 index, JS::Value value)+ {+ auto& observable_array = observable_array_of(array);++ // 1. Let oldLen be handler.[[BackingList]]'s size.+ auto old_length = observable_array.length();++ // 2. Let index be ! ToUint32(P).+ // 3. If index > oldLen, return false.+ if (index > old_length)+ return false;++ if (!can_store(array, JS::PropertyKey { index }))+ return false;++ // NB: Appending also writes the length.+ if (index == old_length && !can_store(array, array.vm().names.length))+ return false;++ // 4. Let idlValue be the result of converting V to the type given by handler.[[Type]].+ TRY(observable_array.run_convert_to_idl_value_callback(value));++ // 5. If index < oldLen, then:+ if (index < old_length) {+ // 1. Perform the algorithm steps given by handler.[[DeleteAlgorithm]], given handler.[[BackingList]][index]+ // and index.+ TRY(observable_array.run_delete_an_indexed_value_callback(index));+ }++ // 6. Perform the algorithm steps given by handler.[[SetAlgorithm]], given idlValue and index.+ TRY(observable_array.run_set_an_indexed_value_callback(index, value));++ // 7. If index = oldLen, then append idlValue to handler.[[BackingList]].+ // 8. Otherwise, set handler.[[BackingList]][index] to idlValue.+ // 9. Return true.+ // NB: [[Set]] would run a setter that script put on the prototype for a missing index, and leave the array+ // without the element. The backing list takes the value directly, so define the element instead.+ JS::PropertyKey property_key { index };+ JS::PropertyDescriptor descriptor { .value = value };+ if (!MUST(array.internal_get_own_property(property_key)).has_value()) {+ descriptor.writable = true;+ descriptor.enumerable = true;+ descriptor.configurable = true;+ }+ return array.internal_define_own_property(property_key, descriptor);+ }};static constexpr JSHostArrayHooks observable_array_hooks = JS::make_host_array_hooks<ObservableArrayHostClassTraits>();@@ -61,10 +215,16 @@ void ObservableArray::visit_edges(JS::Cell::Visitor& visitor)Base::visit_edges(visitor);visitor.visit(m_realm);visitor.visit(m_array_object);+ visitor.visit(m_convert_to_idl_value);visitor.visit(m_on_set_an_indexed_value);visitor.visit(m_on_delete_an_indexed_value);}+void ObservableArray::set_convert_to_idl_value_callback(GC::Ref<GC::Function<ConvertToIDLValueCallbackFunction::FunctionType>> callback)+{+ m_convert_to_idl_value = callback;+}+void ObservableArray::set_on_set_an_indexed_value_callback(GC::Ref<GC::Function<SetAnIndexedValueCallbackFunction::FunctionType>> callback){m_on_set_an_indexed_value = callback;@@ -90,6 +250,14 @@ Optional<JS::Value> ObservableArray::element_value(u32 index) constreturn descriptor->value;}+JS::ThrowCompletionOr<void> ObservableArray::run_convert_to_idl_value_callback(JS::Value value)+{+ if (!m_convert_to_idl_value)+ return {};+ TRY(WebIDL::throw_dom_exception_if_needed(m_realm->vm(), m_realm, [&] { return m_convert_to_idl_value->function()(value); }));+ return {};+}+JS::ThrowCompletionOr<void> ObservableArray::run_set_an_indexed_value_callback(u32 index, JS::Value& value){if (!m_on_set_an_indexed_value)@@ -102,13 +270,17 @@ JS::ThrowCompletionOr<void> ObservableArray::run_delete_an_indexed_value_callbac{if (!m_on_delete_an_indexed_value)return {};- auto deleted_value = element_value(index).value_or(JS::js_undefined());- TRY(WebIDL::throw_dom_exception_if_needed(m_realm->vm(), m_realm, [&] { return m_on_delete_an_indexed_value->function()(deleted_value); }));+ // NB: Object.defineProperty() can leave holes in the array. A hole holds no value to delete.+ auto deleted_value = element_value(index);+ if (!deleted_value.has_value())+ return {};+ TRY(WebIDL::throw_dom_exception_if_needed(m_realm->vm(), m_realm, [&] { return m_on_delete_an_indexed_value->function()(*deleted_value, index); }));return {};}JS::ThrowCompletionOr<void> ObservableArray::append(JS::Value value){+ TRY(run_convert_to_idl_value_callback(value));TRY(run_set_an_indexed_value_callback(length(), value));// Unlike CreateDataProperty, this also appends to an array that script has made non-extensible or frozen.m_array_object->indexed_append(value);@@ -117,12 +289,13 @@ JS::ThrowCompletionOr<void> ObservableArray::append(JS::Value value)void ObservableArray::clear(){- // Each element leaves the array before its callback runs, and the callback may read the elements that remain.- // Unlike [[Delete]], taking an element ignores any attributes that script has given it.+ // Each callback runs while its element is still in the array, as in the deleteProperty trap, and may read the+ // elements that remain. Unlike [[Delete]], taking an element ignores any attributes that script has given it.while (length() != 0) {- auto deleted_value = element_value(0).value_or(JS::js_undefined());+ // NB: A hole holds no value to delete.+ if (auto deleted_value = element_value(0); deleted_value.has_value() && m_on_delete_an_indexed_value)+ MUST(m_on_delete_an_indexed_value->function()(*deleted_value, 0));m_array_object->indexed_take_first();- MUST(m_on_delete_an_indexed_value->function()(deleted_value));}}diff --git a/Libraries/LibWeb/WebIDL/ObservableArray.h b/Libraries/LibWeb/WebIDL/ObservableArray.hindex f063bd6d7cd..caeeb1278d4 100644--- a/Libraries/LibWeb/WebIDL/ObservableArray.h+++ b/Libraries/LibWeb/WebIDL/ObservableArray.h@@ -19,8 +19,8 @@namespace Web::WebIDL {// https://webidl.spec.whatwg.org/#idl-observable-array-// Script sees an observable array as an Array exotic object of its own host class, whose [[Set]] and [[Delete]] run-// the callbacks kept in this companion cell before doing what an Array does.+// Script sees an observable array as an Array exotic object of its own host class, whose [[Set]] and [[Delete]] follow+// the set and deleteProperty traps of observable arrays, running the callbacks kept in this companion cell.class WEB_API ObservableArray final : public JS::Cell {GC_CELL(ObservableArray, JS::Cell);GC_DECLARE_ALLOCATOR(ObservableArray);@@ -30,8 +30,12 @@ public:static GC::Ref<ObservableArray> create(JS::Realm&);+ // Throws if the value does not convert to the type of the elements.+ using ConvertToIDLValueCallbackFunction = Function<ExceptionOr<void>(JS::Value)>;using SetAnIndexedValueCallbackFunction = Function<ExceptionOr<void>(u32 index, JS::Value&)>;- using DeleteAnIndexedValueCallbackFunction = Function<ExceptionOr<void>(JS::Value)>;+ using DeleteAnIndexedValueCallbackFunction = Function<ExceptionOr<void>(JS::Value, u32 index)>;++ void set_convert_to_idl_value_callback(GC::Ref<GC::Function<ConvertToIDLValueCallbackFunction::FunctionType>> callback);void set_on_set_an_indexed_value_callback(GC::Ref<GC::Function<SetAnIndexedValueCallbackFunction::FunctionType>> callback);void set_on_delete_an_indexed_value_callback(GC::Ref<GC::Function<DeleteAnIndexedValueCallbackFunction::FunctionType>> callback);@@ -63,14 +67,17 @@ private:virtual void visit_edges(JS::Cell::Visitor&) override;+ JS::ThrowCompletionOr<void> run_convert_to_idl_value_callback(JS::Value);JS::ThrowCompletionOr<void> run_set_an_indexed_value_callback(u32 index, JS::Value& value);JS::ThrowCompletionOr<void> run_delete_an_indexed_value_callback(u32 index);+ using ConvertToIDLValueCallbackHeapFunction = GC::Function<ConvertToIDLValueCallbackFunction::FunctionType>;using SetAnIndexedValueCallbackHeapFunction = GC::Function<SetAnIndexedValueCallbackFunction::FunctionType>;using DeleteAnIndexedValueCallbackHeapFunction = GC::Function<DeleteAnIndexedValueCallbackFunction::FunctionType>;GC::Ref<JS::Realm> m_realm;GC::Ref<JS::Object> m_array_object;+ GC::Ptr<ConvertToIDLValueCallbackHeapFunction> m_convert_to_idl_value;GC::Ptr<SetAnIndexedValueCallbackHeapFunction> m_on_set_an_indexed_value;GC::Ptr<DeleteAnIndexedValueCallbackHeapFunction> m_on_delete_an_indexed_value;};diff --git a/Tests/LibWeb/Crash/DOM/adopted-style-sheets-with-holes.html b/Tests/LibWeb/Crash/DOM/adopted-style-sheets-with-holes.htmlnew file mode 100644index 00000000000..93e22282d9d--- /dev/null+++ b/Tests/LibWeb/Crash/DOM/adopted-style-sheets-with-holes.html@@ -0,0 +1,6 @@+<!DOCTYPE html>+<script>+ document.adoptedStyleSheets = [new CSSStyleSheet()];+ Object.defineProperty(document.adoptedStyleSheets, "length", { value: 3 });+ document.adoptedStyleSheets = [];+</script>diff --git a/Tests/LibWeb/Text/expected/DOM/adopted-style-sheets-observable-array-operations.txt b/Tests/LibWeb/Text/expected/DOM/adopted-style-sheets-observable-array-operations.txtnew file mode 100644index 00000000000..0e26d133c1c--- /dev/null+++ b/Tests/LibWeb/Text/expected/DOM/adopted-style-sheets-observable-array-operations.txt@@ -0,0 +1,30 @@+adopted red: rgb(255, 0, 0)+grow length: false+fractional length: RangeError+set past the end: false+length: 1+overwrote red with green: rgb(0, 128, 0)+delete first: false+delete length: false+delete last: true+length: 1, color: rgb(0, 128, 0)+shrank length to 0: rgb(0, 0, 0)+removed one of two reds: rgb(255, 0, 0)+removed the last of two reds: rgb(0, 128, 0)+removed the last red after a duplicated sheet: rgb(0, 128, 0)+set null over red: TypeError+after a failed set: rgb(255, 0, 0), length: 1+set a non-constructed sheet over red: NotAllowedError+after a rejected set: rgb(255, 0, 0), length: 1+replaced after defining a non-sheet: rgb(0, 0, 0), length: 0+removed a style element's sheet: rgb(0, 0, 255)+set with a setter on the prototype: rgb(255, 0, 0), own element: true, setter calls: 0+cleared after that: rgb(0, 0, 0)+shrink past a non-configurable sheet: false+delete a non-configurable sheet: false+after failed removals: rgb(255, 0, 0), length: 1+shrink a non-writable length: false+delete with a non-writable length: false+after failed removals: rgb(255, 0, 0), length: 1+append with a non-writable length: false+after a failed append: rgb(255, 0, 0), length: 1diff --git a/Tests/LibWeb/Text/expected/DOM/adopted-style-sheets-replaced-after-define-property.txt b/Tests/LibWeb/Text/expected/DOM/adopted-style-sheets-replaced-after-define-property.txtnew file mode 100644index 00000000000..10aa38ece40--- /dev/null+++ b/Tests/LibWeb/Text/expected/DOM/adopted-style-sheets-replaced-after-define-property.txt@@ -0,0 +1,2 @@+before replacing: rgb(255, 0, 0)+after replacing: rgb(0, 0, 0)diff --git a/Tests/LibWeb/Text/input/DOM/adopted-style-sheets-observable-array-operations.html b/Tests/LibWeb/Text/input/DOM/adopted-style-sheets-observable-array-operations.htmlnew file mode 100644index 00000000000..a6b0f3468b6--- /dev/null+++ b/Tests/LibWeb/Text/input/DOM/adopted-style-sheets-observable-array-operations.html@@ -0,0 +1,93 @@+<!DOCTYPE html>+<style>#target { background-color: blue }</style>+<div id="target"></div>+<script src="../include.js"></script>+<script>+ test(() => {+ const red = new CSSStyleSheet();+ red.replaceSync("#target { color: red }");+ const green = new CSSStyleSheet();+ green.replaceSync("#target { color: green }");+ const sheets = () => document.adoptedStyleSheets;+ const color = () => getComputedStyle(target).color;+ const attempt = (name, operation) => {+ try {+ println(`${name}: ${operation()}`);+ } catch (e) {+ println(`${name}: ${e.name}`);+ }+ };++ document.adoptedStyleSheets = [red];+ println(`adopted red: ${color()}`);++ attempt("grow length", () => Reflect.set(sheets(), "length", 3));+ attempt("fractional length", () => Reflect.set(sheets(), "length", 0.5));+ attempt("set past the end", () => Reflect.set(sheets(), 5, green));+ println(`length: ${sheets().length}`);++ sheets()[0] = green;+ println(`overwrote red with green: ${color()}`);++ sheets().push(red);+ attempt("delete first", () => Reflect.deleteProperty(sheets(), 0));+ attempt("delete length", () => Reflect.deleteProperty(sheets(), "length"));+ attempt("delete last", () => Reflect.deleteProperty(sheets(), 1));+ println(`length: ${sheets().length}, color: ${color()}`);++ sheets().length = 0;+ println(`shrank length to 0: ${color()}`);++ document.adoptedStyleSheets = [red, red];+ sheets().length = 1;+ println(`removed one of two reds: ${color()}`);++ document.adoptedStyleSheets = [red, green, red];+ sheets().length = 2;+ println(`removed the last of two reds: ${color()}`);++ const empty = new CSSStyleSheet();+ document.adoptedStyleSheets = [red, empty, green, empty, red];+ sheets().length = 4;+ println(`removed the last red after a duplicated sheet: ${color()}`);++ document.adoptedStyleSheets = [red];+ attempt("set null over red", () => Reflect.set(sheets(), 0, null));+ println(`after a failed set: ${color()}, length: ${sheets().length}`);+ attempt("set a non-constructed sheet over red", () => Reflect.set(sheets(), 0, document.styleSheets[0]));+ println(`after a rejected set: ${color()}, length: ${sheets().length}`);++ document.adoptedStyleSheets = [red];+ Object.defineProperty(sheets(), 1, { value: 1, writable: true, enumerable: true, configurable: true });+ document.adoptedStyleSheets = [];+ println(`replaced after defining a non-sheet: ${color()}, length: ${sheets().length}`);++ document.adoptedStyleSheets = [];+ Object.defineProperty(sheets(), 0, { value: document.styleSheets[0], writable: true, enumerable: true, configurable: true });+ sheets().length = 0;+ println(`removed a style element's sheet: ${getComputedStyle(target).backgroundColor}`);++ let setterCalls = 0;+ const prototype = Object.create(Array.prototype, { 0: { set() { ++setterCalls; } } });+ Object.setPrototypeOf(sheets(), prototype);+ sheets()[0] = red;+ println(`set with a setter on the prototype: ${color()}, own element: ${Object.hasOwn(sheets(), 0)}, setter calls: ${setterCalls}`);+ document.adoptedStyleSheets = [];+ println(`cleared after that: ${color()}`);+ Object.setPrototypeOf(sheets(), Array.prototype);++ document.adoptedStyleSheets = [red];+ Object.defineProperty(sheets(), 0, { configurable: false });+ attempt("shrink past a non-configurable sheet", () => Reflect.set(sheets(), "length", 0));+ attempt("delete a non-configurable sheet", () => Reflect.deleteProperty(sheets(), 0));+ println(`after failed removals: ${color()}, length: ${sheets().length}`);++ document.adoptedStyleSheets = [red];+ Object.defineProperty(sheets(), "length", { writable: false });+ attempt("shrink a non-writable length", () => Reflect.set(sheets(), "length", 0));+ attempt("delete with a non-writable length", () => Reflect.deleteProperty(sheets(), 0));+ println(`after failed removals: ${color()}, length: ${sheets().length}`);+ attempt("append with a non-writable length", () => Reflect.set(sheets(), 1, green));+ println(`after a failed append: ${color()}, length: ${sheets().length}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/DOM/adopted-style-sheets-replaced-after-define-property.html b/Tests/LibWeb/Text/input/DOM/adopted-style-sheets-replaced-after-define-property.htmlnew file mode 100644index 00000000000..6433af9bbdb--- /dev/null+++ b/Tests/LibWeb/Text/input/DOM/adopted-style-sheets-replaced-after-define-property.html@@ -0,0 +1,15 @@+<!DOCTYPE html>+<div id="target"></div>+<script src="../include.js"></script>+<script>+ test(() => {+ const first = new CSSStyleSheet();+ const second = new CSSStyleSheet();+ second.replaceSync("#target { color: red }");+ document.adoptedStyleSheets = [first, second];+ Object.defineProperty(document.adoptedStyleSheets, 0, { writable: false });+ println(`before replacing: ${getComputedStyle(target).color}`);+ document.adoptedStyleSheets = [];+ println(`after replacing: ${getComputedStyle(target).color}`);+ });+</script>