UniversalGlobalScope.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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, and if callback throws an exception, report the exception.
  74. HTML::queue_a_microtask(document, GC::create_function(realm.heap(), [&callback, &realm] {
  75. auto result = WebIDL::invoke_callback(callback, {});
  76. if (result.is_error())
  77. HTML::report_exception(result, realm);
  78. }));
  79. }
  80. // https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
  81. WebIDL::ExceptionOr<JS::Value> UniversalGlobalScopeMixin::structured_clone(JS::Value value, StructuredSerializeOptions const& options) const
  82. {
  83. auto& vm = this_impl().vm();
  84. (void)options;
  85. // 1. Let serialized be ? StructuredSerializeWithTransfer(value, options["transfer"]).
  86. // FIXME: Use WithTransfer variant of the AO
  87. auto serialized = TRY(structured_serialize(vm, value));
  88. // 2. Let deserializeRecord be ? StructuredDeserializeWithTransfer(serialized, this's relevant realm).
  89. // FIXME: Use WithTransfer variant of the AO
  90. auto deserialized = TRY(structured_deserialize(vm, serialized, relevant_realm(this_impl())));
  91. // 3. Return deserializeRecord.[[Deserialized]].
  92. return deserialized;
  93. }
  94. // https://streams.spec.whatwg.org/#count-queuing-strategy-size-function
  95. GC::Ref<WebIDL::CallbackType> UniversalGlobalScopeMixin::count_queuing_strategy_size_function()
  96. {
  97. auto& realm = HTML::relevant_realm(this_impl());
  98. if (!m_count_queuing_strategy_size_function) {
  99. // 1. Let steps be the following steps:
  100. auto steps = [](auto const&) {
  101. // 1. Return 1.
  102. return 1.0;
  103. };
  104. // 2. Let F be ! CreateBuiltinFunction(steps, 0, "size", « », globalObject’s relevant Realm).
  105. auto function = JS::NativeFunction::create(realm, move(steps), 0, "size", &realm);
  106. // 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.
  107. // FIXME: Update spec comment to pass globalObject's relevant realm once Streams spec is updated for ShadowRealm spec
  108. m_count_queuing_strategy_size_function = realm.create<WebIDL::CallbackType>(*function, realm);
  109. }
  110. return GC::Ref { *m_count_queuing_strategy_size_function };
  111. }
  112. // https://streams.spec.whatwg.org/#byte-length-queuing-strategy-size-function
  113. GC::Ref<WebIDL::CallbackType> UniversalGlobalScopeMixin::byte_length_queuing_strategy_size_function()
  114. {
  115. auto& realm = HTML::relevant_realm(this_impl());
  116. if (!m_byte_length_queuing_strategy_size_function) {
  117. // 1. Let steps be the following steps, given chunk:
  118. auto steps = [](JS::VM& vm) {
  119. auto chunk = vm.argument(0);
  120. // 1. Return ? GetV(chunk, "byteLength").
  121. return chunk.get(vm, vm.names.byteLength);
  122. };
  123. // 2. Let F be ! CreateBuiltinFunction(steps, 1, "size", « », globalObject’s relevant Realm).
  124. auto function = JS::NativeFunction::create(realm, move(steps), 1, "size", &realm);
  125. // 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.
  126. // FIXME: Update spec comment to pass globalObject's relevant realm once Streams spec is updated for ShadowRealm spec
  127. m_byte_length_queuing_strategy_size_function = realm.create<WebIDL::CallbackType>(*function, realm);
  128. }
  129. return GC::Ref { *m_byte_length_queuing_strategy_size_function };
  130. }
  131. void UniversalGlobalScopeMixin::push_onto_outstanding_rejected_promises_weak_set(JS::Promise* promise)
  132. {
  133. m_outstanding_rejected_promises_weak_set.append(promise);
  134. }
  135. bool UniversalGlobalScopeMixin::remove_from_outstanding_rejected_promises_weak_set(JS::Promise* promise)
  136. {
  137. return m_outstanding_rejected_promises_weak_set.remove_first_matching([&](JS::Promise* promise_in_set) {
  138. return promise == promise_in_set;
  139. });
  140. }
  141. void UniversalGlobalScopeMixin::push_onto_about_to_be_notified_rejected_promises_list(GC::Ref<JS::Promise> promise)
  142. {
  143. m_about_to_be_notified_rejected_promises_list.append(GC::make_root(promise));
  144. }
  145. bool UniversalGlobalScopeMixin::remove_from_about_to_be_notified_rejected_promises_list(GC::Ref<JS::Promise> promise)
  146. {
  147. return m_about_to_be_notified_rejected_promises_list.remove_first_matching([&](auto& promise_in_list) {
  148. return promise == promise_in_list;
  149. });
  150. }
  151. // https://html.spec.whatwg.org/multipage/webappapis.html#notify-about-rejected-promises
  152. void UniversalGlobalScopeMixin::notify_about_rejected_promises(Badge<EventLoop>)
  153. {
  154. auto& realm = this_impl().realm();
  155. // 1. Let list be a copy of settings object's about-to-be-notified rejected promises list.
  156. auto list = m_about_to_be_notified_rejected_promises_list;
  157. // 2. If list is empty, return.
  158. if (list.is_empty())
  159. return;
  160. // 3. Clear settings object's about-to-be-notified rejected promises list.
  161. m_about_to_be_notified_rejected_promises_list.clear();
  162. // 4. Let global be settings object's global object.
  163. auto& global = this_impl();
  164. // 5. Queue a global task on the DOM manipulation task source given global to run the following substep:
  165. queue_global_task(Task::Source::DOMManipulation, global, GC::create_function(realm.heap(), [this, &global, list = move(list)] {
  166. auto& realm = global.realm();
  167. // 1. For each promise p in list:
  168. for (auto const& promise : list) {
  169. // 1. If p's [[PromiseIsHandled]] internal slot is true, continue to the next iteration of the loop.
  170. if (promise->is_handled())
  171. continue;
  172. // 2. Let notHandled be the result of firing an event named unhandledrejection at global, using PromiseRejectionEvent, with the cancelable attribute initialized to true,
  173. // the promise attribute initialized to p, and the reason attribute initialized to the value of p's [[PromiseResult]] internal slot.
  174. PromiseRejectionEventInit event_init {
  175. {
  176. .bubbles = false,
  177. .cancelable = true,
  178. .composed = false,
  179. },
  180. // Sadly we can't use .promise and .reason here, as we can't use the designator on the initialization of DOM::EventInit above.
  181. /* .promise = */ *promise,
  182. /* .reason = */ promise->result(),
  183. };
  184. auto promise_rejection_event = PromiseRejectionEvent::create(realm, HTML::EventNames::unhandledrejection, event_init);
  185. bool not_handled = global.dispatch_event(*promise_rejection_event);
  186. // 3. If notHandled is false, then the promise rejection is handled. Otherwise, the promise rejection is not handled.
  187. // 4. If p's [[PromiseIsHandled]] internal slot is false, add p to settings object's outstanding rejected promises weak set.
  188. if (!promise->is_handled())
  189. m_outstanding_rejected_promises_weak_set.append(*promise);
  190. // This algorithm results in promise rejections being marked as handled or not handled. These concepts parallel handled and not handled script errors.
  191. // If a rejection is still not handled after this, then the rejection may be reported to a developer console.
  192. if (not_handled)
  193. HTML::report_exception_to_console(promise->result(), realm, ErrorInPromise::Yes);
  194. }
  195. }));
  196. }
  197. }