UniversalGlobalScope.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. /*
  2. * Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
  3. * Copyright (c) 2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  5. * Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/Base64.h>
  10. #include <AK/String.h>
  11. #include <AK/Utf8View.h>
  12. #include <AK/Vector.h>
  13. #include <LibGC/Function.h>
  14. #include <LibJS/Runtime/NativeFunction.h>
  15. #include <LibWeb/HTML/PromiseRejectionEvent.h>
  16. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  17. #include <LibWeb/HTML/StructuredSerialize.h>
  18. #include <LibWeb/HTML/StructuredSerializeOptions.h>
  19. #include <LibWeb/HTML/UniversalGlobalScope.h>
  20. #include <LibWeb/HTML/Window.h>
  21. #include <LibWeb/Infra/Strings.h>
  22. #include <LibWeb/WebIDL/AbstractOperations.h>
  23. #include <LibWeb/WebIDL/DOMException.h>
  24. #include <LibWeb/WebIDL/ExceptionOr.h>
  25. #include <LibWeb/WebIDL/Types.h>
  26. namespace Web::HTML {
  27. UniversalGlobalScopeMixin::~UniversalGlobalScopeMixin() = default;
  28. void UniversalGlobalScopeMixin::visit_edges(GC::Cell::Visitor& visitor)
  29. {
  30. visitor.visit(m_count_queuing_strategy_size_function);
  31. visitor.visit(m_byte_length_queuing_strategy_size_function);
  32. visitor.ignore(m_outstanding_rejected_promises_weak_set);
  33. }
  34. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-btoa
  35. WebIDL::ExceptionOr<String> UniversalGlobalScopeMixin::btoa(String const& data) const
  36. {
  37. auto& vm = this_impl().vm();
  38. auto& realm = *vm.current_realm();
  39. // The btoa(data) method must throw an "InvalidCharacterError" DOMException if data contains any character whose code point is greater than U+00FF.
  40. Vector<u8> byte_string;
  41. byte_string.ensure_capacity(data.bytes().size());
  42. for (u32 code_point : Utf8View(data)) {
  43. if (code_point > 0xff)
  44. return WebIDL::InvalidCharacterError::create(realm, "Data contains characters outside the range U+0000 and U+00FF"_string);
  45. byte_string.append(code_point);
  46. }
  47. // Otherwise, the user agent must convert data to a byte sequence whose nth byte is the eight-bit representation of the nth code point of data,
  48. // and then must apply forgiving-base64 encode to that byte sequence and return the result.
  49. return TRY_OR_THROW_OOM(vm, encode_base64(byte_string.span()));
  50. }
  51. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob
  52. WebIDL::ExceptionOr<String> UniversalGlobalScopeMixin::atob(String const& data) const
  53. {
  54. auto& vm = this_impl().vm();
  55. auto& realm = *vm.current_realm();
  56. // 1. Let decodedData be the result of running forgiving-base64 decode on data.
  57. auto decoded_data = decode_base64(data);
  58. // 2. If decodedData is failure, then throw an "InvalidCharacterError" DOMException.
  59. if (decoded_data.is_error())
  60. return WebIDL::InvalidCharacterError::create(realm, "Input string is not valid base64 data"_string);
  61. // 3. Return decodedData.
  62. // decode_base64() returns a byte buffer. LibJS uses UTF-8 for strings. Use isomorphic decoding to convert bytes to UTF-8.
  63. return Infra::isomorphic_decode(decoded_data.value());
  64. }
  65. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-queuemicrotask
  66. void UniversalGlobalScopeMixin::queue_microtask(WebIDL::CallbackType& callback)
  67. {
  68. auto& vm = this_impl().vm();
  69. auto& realm = *vm.current_realm();
  70. GC::Ptr<DOM::Document> document;
  71. if (is<Window>(this_impl()))
  72. document = &static_cast<Window&>(this_impl()).associated_document();
  73. // The queueMicrotask(callback) method must queue a microtask to invoke callback with « » and "report".
  74. HTML::queue_a_microtask(document, GC::create_function(realm.heap(), [&callback] {
  75. (void)WebIDL::invoke_callback(callback, {}, WebIDL::ExceptionBehavior::Report);
  76. }));
  77. }
  78. // https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
  79. WebIDL::ExceptionOr<JS::Value> UniversalGlobalScopeMixin::structured_clone(JS::Value value, StructuredSerializeOptions const& options) const
  80. {
  81. auto& vm = this_impl().vm();
  82. (void)options;
  83. // 1. Let serialized be ? StructuredSerializeWithTransfer(value, options["transfer"]).
  84. // FIXME: Use WithTransfer variant of the AO
  85. auto serialized = TRY(structured_serialize(vm, value));
  86. // 2. Let deserializeRecord be ? StructuredDeserializeWithTransfer(serialized, this's relevant realm).
  87. // FIXME: Use WithTransfer variant of the AO
  88. auto deserialized = TRY(structured_deserialize(vm, serialized, relevant_realm(this_impl())));
  89. // 3. Return deserializeRecord.[[Deserialized]].
  90. return deserialized;
  91. }
  92. // https://streams.spec.whatwg.org/#count-queuing-strategy-size-function
  93. GC::Ref<WebIDL::CallbackType> UniversalGlobalScopeMixin::count_queuing_strategy_size_function()
  94. {
  95. auto& realm = HTML::relevant_realm(this_impl());
  96. if (!m_count_queuing_strategy_size_function) {
  97. // 1. Let steps be the following steps:
  98. auto steps = [](auto const&) {
  99. // 1. Return 1.
  100. return 1.0;
  101. };
  102. // 2. Let F be ! CreateBuiltinFunction(steps, 0, "size", « », globalObject’s relevant Realm).
  103. auto function = JS::NativeFunction::create(realm, move(steps), 0, "size", &realm);
  104. // 3. Set globalObject’s count queuing strategy size function to a Function that represents a reference to F, with callback context equal to globalObject’s relevant settings object.
  105. // FIXME: Update spec comment to pass globalObject's relevant realm once Streams spec is updated for ShadowRealm spec
  106. m_count_queuing_strategy_size_function = realm.create<WebIDL::CallbackType>(*function, realm);
  107. }
  108. return GC::Ref { *m_count_queuing_strategy_size_function };
  109. }
  110. // https://streams.spec.whatwg.org/#byte-length-queuing-strategy-size-function
  111. GC::Ref<WebIDL::CallbackType> UniversalGlobalScopeMixin::byte_length_queuing_strategy_size_function()
  112. {
  113. auto& realm = HTML::relevant_realm(this_impl());
  114. if (!m_byte_length_queuing_strategy_size_function) {
  115. // 1. Let steps be the following steps, given chunk:
  116. auto steps = [](JS::VM& vm) {
  117. auto chunk = vm.argument(0);
  118. // 1. Return ? GetV(chunk, "byteLength").
  119. return chunk.get(vm, vm.names.byteLength);
  120. };
  121. // 2. Let F be ! CreateBuiltinFunction(steps, 1, "size", « », globalObject’s relevant Realm).
  122. auto function = JS::NativeFunction::create(realm, move(steps), 1, "size", &realm);
  123. // 3. Set globalObject’s byte length queuing strategy size function to a Function that represents a reference to F, with callback context equal to globalObject’s relevant settings object.
  124. // FIXME: Update spec comment to pass globalObject's relevant realm once Streams spec is updated for ShadowRealm spec
  125. m_byte_length_queuing_strategy_size_function = realm.create<WebIDL::CallbackType>(*function, realm);
  126. }
  127. return GC::Ref { *m_byte_length_queuing_strategy_size_function };
  128. }
  129. void UniversalGlobalScopeMixin::push_onto_outstanding_rejected_promises_weak_set(JS::Promise* promise)
  130. {
  131. m_outstanding_rejected_promises_weak_set.append(promise);
  132. }
  133. bool UniversalGlobalScopeMixin::remove_from_outstanding_rejected_promises_weak_set(JS::Promise* promise)
  134. {
  135. return m_outstanding_rejected_promises_weak_set.remove_first_matching([&](JS::Promise* promise_in_set) {
  136. return promise == promise_in_set;
  137. });
  138. }
  139. void UniversalGlobalScopeMixin::push_onto_about_to_be_notified_rejected_promises_list(GC::Ref<JS::Promise> promise)
  140. {
  141. m_about_to_be_notified_rejected_promises_list.append(GC::make_root(promise));
  142. }
  143. bool UniversalGlobalScopeMixin::remove_from_about_to_be_notified_rejected_promises_list(GC::Ref<JS::Promise> promise)
  144. {
  145. return m_about_to_be_notified_rejected_promises_list.remove_first_matching([&](auto& promise_in_list) {
  146. return promise == promise_in_list;
  147. });
  148. }
  149. // https://html.spec.whatwg.org/multipage/webappapis.html#notify-about-rejected-promises
  150. void UniversalGlobalScopeMixin::notify_about_rejected_promises(Badge<EventLoop>)
  151. {
  152. auto& realm = this_impl().realm();
  153. // 1. Let list be a copy of settings object's about-to-be-notified rejected promises list.
  154. auto list = m_about_to_be_notified_rejected_promises_list;
  155. // 2. If list is empty, return.
  156. if (list.is_empty())
  157. return;
  158. // 3. Clear settings object's about-to-be-notified rejected promises list.
  159. m_about_to_be_notified_rejected_promises_list.clear();
  160. // 4. Let global be settings object's global object.
  161. auto& global = this_impl();
  162. // 5. Queue a global task on the DOM manipulation task source given global to run the following substep:
  163. queue_global_task(Task::Source::DOMManipulation, global, GC::create_function(realm.heap(), [this, &global, list = move(list)] {
  164. auto& realm = global.realm();
  165. // 1. For each promise p in list:
  166. for (auto const& promise : list) {
  167. // 1. If p's [[PromiseIsHandled]] internal slot is true, continue to the next iteration of the loop.
  168. if (promise->is_handled())
  169. continue;
  170. // 2. Let notHandled be the result of firing an event named unhandledrejection at global, using PromiseRejectionEvent, with the cancelable attribute initialized to true,
  171. // the promise attribute initialized to p, and the reason attribute initialized to the value of p's [[PromiseResult]] internal slot.
  172. PromiseRejectionEventInit event_init {
  173. {
  174. .bubbles = false,
  175. .cancelable = true,
  176. .composed = false,
  177. },
  178. // Sadly we can't use .promise and .reason here, as we can't use the designator on the initialization of DOM::EventInit above.
  179. /* .promise = */ *promise,
  180. /* .reason = */ promise->result(),
  181. };
  182. auto promise_rejection_event = PromiseRejectionEvent::create(realm, HTML::EventNames::unhandledrejection, event_init);
  183. bool not_handled = global.dispatch_event(*promise_rejection_event);
  184. // 3. If notHandled is false, then the promise rejection is handled. Otherwise, the promise rejection is not handled.
  185. // 4. If p's [[PromiseIsHandled]] internal slot is false, add p to settings object's outstanding rejected promises weak set.
  186. if (!promise->is_handled())
  187. m_outstanding_rejected_promises_weak_set.append(*promise);
  188. // This algorithm results in promise rejections being marked as handled or not handled. These concepts parallel handled and not handled script errors.
  189. // If a rejection is still not handled after this, then the rejection may be reported to a developer console.
  190. if (not_handled)
  191. HTML::report_exception_to_console(promise->result(), realm, ErrorInPromise::Yes);
  192. }
  193. }));
  194. }
  195. }