ExecuteScript.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/JsonArray.h>
  7. #include <AK/JsonObject.h>
  8. #include <AK/JsonValue.h>
  9. #include <AK/NumericLimits.h>
  10. #include <AK/ScopeGuard.h>
  11. #include <AK/Time.h>
  12. #include <AK/Variant.h>
  13. #include <LibJS/Parser.h>
  14. #include <LibJS/Runtime/Array.h>
  15. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  16. #include <LibJS/Runtime/GlobalEnvironment.h>
  17. #include <LibJS/Runtime/JSONObject.h>
  18. #include <LibJS/Runtime/Promise.h>
  19. #include <LibJS/Runtime/PromiseConstructor.h>
  20. #include <LibWeb/DOM/Document.h>
  21. #include <LibWeb/DOM/HTMLCollection.h>
  22. #include <LibWeb/DOM/NodeList.h>
  23. #include <LibWeb/FileAPI/FileList.h>
  24. #include <LibWeb/HTML/BrowsingContext.h>
  25. #include <LibWeb/HTML/HTMLOptionsCollection.h>
  26. #include <LibWeb/HTML/Scripting/Environments.h>
  27. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  28. #include <LibWeb/HTML/Window.h>
  29. #include <LibWeb/HTML/WindowProxy.h>
  30. #include <LibWeb/Page/Page.h>
  31. #include <LibWeb/Platform/EventLoopPlugin.h>
  32. #include <LibWeb/WebDriver/Contexts.h>
  33. #include <LibWeb/WebDriver/ExecuteScript.h>
  34. namespace Web::WebDriver {
  35. #define TRY_OR_JS_ERROR(expression) \
  36. ({ \
  37. auto&& _temporary_result = (expression); \
  38. if (_temporary_result.is_error()) [[unlikely]] \
  39. return ExecuteScriptResultType::JavaScriptError; \
  40. static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
  41. "Do not return a reference from a fallible expression"); \
  42. _temporary_result.release_value(); \
  43. })
  44. static ErrorOr<JsonValue, ExecuteScriptResultType> internal_json_clone_algorithm(JS::Realm&, JS::Value, HashTable<JS::Object*>& seen);
  45. static ErrorOr<JsonValue, ExecuteScriptResultType> clone_an_object(JS::Realm&, JS::Object&, HashTable<JS::Object*>& seen, auto const& clone_algorithm);
  46. // https://w3c.github.io/webdriver/#dfn-collection
  47. static bool is_collection(JS::Object const& value)
  48. {
  49. // A collection is an Object that implements the Iterable interface, and whose:
  50. return (
  51. // - initial value of the toString own property is "Arguments"
  52. value.has_parameter_map()
  53. // - instance of Array
  54. || is<JS::Array>(value)
  55. // - instance of FileList
  56. || is<FileAPI::FileList>(value)
  57. // - instance of HTMLAllCollection
  58. || false // FIXME
  59. // - instance of HTMLCollection
  60. || is<DOM::HTMLCollection>(value)
  61. // - instance of HTMLFormControlsCollection
  62. || false // FIXME
  63. // - instance of HTMLOptionsCollection
  64. || is<HTML::HTMLOptionsCollection>(value)
  65. // - instance of NodeList
  66. || is<DOM::NodeList>(value));
  67. }
  68. // https://w3c.github.io/webdriver/#dfn-json-clone
  69. static ErrorOr<JsonValue, ExecuteScriptResultType> json_clone(JS::Realm& realm, JS::Value value)
  70. {
  71. // To perform a JSON clone return the result of calling the internal JSON clone algorithm with arguments value and an empty List.
  72. auto seen = HashTable<JS::Object*> {};
  73. return internal_json_clone_algorithm(realm, value, seen);
  74. }
  75. // https://w3c.github.io/webdriver/#dfn-internal-json-clone-algorithm
  76. static ErrorOr<JsonValue, ExecuteScriptResultType> internal_json_clone_algorithm(JS::Realm& realm, JS::Value value, HashTable<JS::Object*>& seen)
  77. {
  78. auto& vm = realm.vm();
  79. // When required to run the internal JSON clone algorithm with arguments value and seen, a remote end must return the value of the first matching statement, matching on value:
  80. // -> undefined
  81. // -> null
  82. if (value.is_nullish()) {
  83. // Success with data null.
  84. return JsonValue {};
  85. }
  86. // -> type Boolean
  87. // -> type Number
  88. // -> type String
  89. // Success with data value.
  90. if (value.is_boolean())
  91. return JsonValue { value.as_bool() };
  92. if (value.is_number())
  93. return JsonValue { value.as_double() };
  94. if (value.is_string())
  95. return JsonValue { value.as_string().byte_string() };
  96. // NOTE: BigInt and Symbol not mentioned anywhere in the WebDriver spec, as it references ES5.
  97. // It assumes that all primitives are handled above, and the value is an object for the remaining steps.
  98. if (value.is_bigint() || value.is_symbol())
  99. return ExecuteScriptResultType::JavaScriptError;
  100. // FIXME: -> a collection
  101. // FIXME: -> instance of element
  102. // FIXME: -> instance of shadow root
  103. // -> a WindowProxy object
  104. if (is<HTML::WindowProxy>(value.as_object())) {
  105. auto const& window_proxy = static_cast<HTML::WindowProxy&>(value.as_object());
  106. // If the associated browsing context of the WindowProxy object in value has been destroyed, return error with
  107. // error code stale element reference.
  108. if (window_proxy.associated_browsing_context()->has_navigable_been_destroyed())
  109. return ExecuteScriptResultType::BrowsingContextDiscarded;
  110. // Otherwise return success with data set to WindowProxy reference object for value.
  111. return window_proxy_reference_object(window_proxy);
  112. }
  113. // -> has an own property named "toJSON" that is a Function
  114. auto to_json = value.as_object().get_without_side_effects(vm.names.toJSON);
  115. if (to_json.is_function()) {
  116. // Return success with the value returned by Function.[[Call]](toJSON) with value as the this value.
  117. auto to_json_result = TRY_OR_JS_ERROR(to_json.as_function().internal_call(value, JS::MarkedVector<JS::Value> { vm.heap() }));
  118. if (!to_json_result.is_string())
  119. return ExecuteScriptResultType::JavaScriptError;
  120. return to_json_result.as_string().byte_string();
  121. }
  122. // -> Otherwise
  123. // 1. If value is in seen, return error with error code javascript error.
  124. if (seen.contains(&value.as_object()))
  125. return ExecuteScriptResultType::JavaScriptError;
  126. // 2. Append value to seen.
  127. seen.set(&value.as_object());
  128. ScopeGuard remove_seen { [&] {
  129. // 4. Remove the last element of seen.
  130. seen.remove(&value.as_object());
  131. } };
  132. // 3. Let result be the value of running the clone an object algorithm with arguments value and seen, and the internal JSON clone algorithm as the clone algorithm.
  133. auto result = TRY(clone_an_object(realm, value.as_object(), seen, internal_json_clone_algorithm));
  134. // 5. Return result.
  135. return result;
  136. }
  137. // https://w3c.github.io/webdriver/#dfn-clone-an-object
  138. static ErrorOr<JsonValue, ExecuteScriptResultType> clone_an_object(JS::Realm& realm, JS::Object& value, HashTable<JS::Object*>& seen, auto const& clone_algorithm)
  139. {
  140. auto& vm = realm.vm();
  141. // 1. Let result be the value of the first matching statement, matching on value:
  142. auto get_result = [&]() -> ErrorOr<Variant<JsonArray, JsonObject>, ExecuteScriptResultType> {
  143. // -> a collection
  144. if (is_collection(value)) {
  145. // A new Array which length property is equal to the result of getting the property length of value.
  146. auto length_property = TRY_OR_JS_ERROR(value.internal_get_own_property(vm.names.length));
  147. if (!length_property->value.has_value())
  148. return ExecuteScriptResultType::JavaScriptError;
  149. auto length = TRY_OR_JS_ERROR(length_property->value->to_length(vm));
  150. if (length > NumericLimits<u32>::max())
  151. return ExecuteScriptResultType::JavaScriptError;
  152. auto array = JsonArray {};
  153. for (size_t i = 0; i < length; ++i)
  154. array.must_append(JsonValue {});
  155. return array;
  156. }
  157. // -> Otherwise
  158. else {
  159. // A new Object.
  160. return JsonObject {};
  161. }
  162. };
  163. auto result = TRY(get_result());
  164. // 2. For each enumerable own property in value, run the following substeps:
  165. for (auto& key : MUST(value.Object::internal_own_property_keys())) {
  166. // 1. Let name be the name of the property.
  167. auto name = MUST(JS::PropertyKey::from_value(vm, key));
  168. if (!value.storage_get(name)->attributes.is_enumerable())
  169. continue;
  170. // 2. Let source property value be the result of getting a property named name from value. If doing so causes script to be run and that script throws an error, return error with error code javascript error.
  171. auto source_property_value = TRY_OR_JS_ERROR(value.internal_get_own_property(name));
  172. if (!source_property_value.has_value() || !source_property_value->value.has_value())
  173. continue;
  174. // 3. Let cloned property result be the result of calling the clone algorithm with arguments source property value and seen.
  175. auto cloned_property_result = clone_algorithm(realm, *source_property_value->value, seen);
  176. // 4. If cloned property result is a success, set a property of result with name name and value equal to cloned property result’s data.
  177. if (!cloned_property_result.is_error()) {
  178. result.visit(
  179. [&](JsonArray& array) {
  180. // NOTE: If this was a JS array, only indexed properties would be serialized anyway.
  181. if (name.is_number())
  182. array.set(name.as_number(), cloned_property_result.value());
  183. },
  184. [&](JsonObject& object) {
  185. object.set(name.to_string(), cloned_property_result.value());
  186. });
  187. }
  188. // 5. Otherwise, return cloned property result.
  189. else {
  190. return cloned_property_result;
  191. }
  192. }
  193. return result.visit([&](auto const& value) -> JsonValue { return value; });
  194. }
  195. // https://w3c.github.io/webdriver/#dfn-execute-a-function-body
  196. static JS::ThrowCompletionOr<JS::Value> execute_a_function_body(HTML::BrowsingContext const& browsing_context, ByteString const& body, JS::MarkedVector<JS::Value> parameters)
  197. {
  198. // FIXME: If at any point during the algorithm a user prompt appears, immediately return Completion { [[Type]]: normal, [[Value]]: null, [[Target]]: empty }, but continue to run the other steps of this algorithm in parallel.
  199. // 1. Let window be the associated window of the current browsing context’s active document.
  200. auto window = browsing_context.active_document()->window();
  201. // 2. Let environment settings be the environment settings object for window.
  202. auto& environment_settings = Web::HTML::relevant_settings_object(*window);
  203. // 3. Let global scope be environment settings realm’s global environment.
  204. auto& global_scope = environment_settings.realm().global_environment();
  205. auto& realm = window->realm();
  206. auto source_text = ByteString::formatted("function() {{ {} }}", body);
  207. auto parser = JS::Parser { JS::Lexer { source_text } };
  208. auto function_expression = parser.parse_function_node<JS::FunctionExpression>();
  209. // 4. If body is not parsable as a FunctionBody or if parsing detects an early error, return Completion { [[Type]]: normal, [[Value]]: null, [[Target]]: empty }.
  210. if (parser.has_errors())
  211. return JS::js_null();
  212. // 5. If body begins with a directive prologue that contains a use strict directive then let strict be true, otherwise let strict be false.
  213. // NOTE: Handled in step 8 below.
  214. // 6. Prepare to run a script with environment settings.
  215. environment_settings.prepare_to_run_script();
  216. // 7. Prepare to run a callback with environment settings.
  217. environment_settings.prepare_to_run_callback();
  218. // 8. Let function be the result of calling FunctionCreate, with arguments:
  219. // kind
  220. // Normal.
  221. // list
  222. // An empty List.
  223. // body
  224. // The result of parsing body above.
  225. // global scope
  226. // The result of parsing global scope above.
  227. // strict
  228. // The result of parsing strict above.
  229. auto function = JS::ECMAScriptFunctionObject::create(realm, "", move(source_text), function_expression->body(), function_expression->parameters(), function_expression->function_length(), function_expression->local_variables_names(), &global_scope, nullptr, function_expression->kind(), function_expression->is_strict_mode(), function_expression->parsing_insights());
  230. // 9. Let completion be Function.[[Call]](window, parameters) with function as the this value.
  231. // NOTE: This is not entirely clear, but I don't think they mean actually passing `function` as
  232. // the this value argument, but using it as the object [[Call]] is executed on.
  233. auto completion = function->internal_call(window, move(parameters));
  234. // 10. Clean up after running a callback with environment settings.
  235. environment_settings.clean_up_after_running_callback();
  236. // 11. Clean up after running a script with environment settings.
  237. environment_settings.clean_up_after_running_script();
  238. // 12. Return completion.
  239. return completion;
  240. }
  241. class HeapTimer : public JS::Cell {
  242. JS_CELL(HeapTimer, JS::Cell);
  243. JS_DECLARE_ALLOCATOR(HeapTimer);
  244. public:
  245. explicit HeapTimer()
  246. : m_timer(Core::Timer::create())
  247. {
  248. }
  249. virtual ~HeapTimer() override = default;
  250. void start(u64 timeout_ms, JS::NonnullGCPtr<OnScriptComplete> on_timeout)
  251. {
  252. m_on_timeout = on_timeout;
  253. m_timer->on_timeout = [this]() {
  254. m_timed_out = true;
  255. if (m_on_timeout) {
  256. auto error_object = JsonObject {};
  257. error_object.set("name", "Error");
  258. error_object.set("message", "Script Timeout");
  259. m_on_timeout->function()({ ExecuteScriptResultType::Timeout, move(error_object) });
  260. m_on_timeout = nullptr;
  261. }
  262. };
  263. m_timer->set_interval(static_cast<int>(timeout_ms));
  264. m_timer->set_single_shot(true);
  265. m_timer->start();
  266. }
  267. void stop()
  268. {
  269. m_on_timeout = nullptr;
  270. m_timer->stop();
  271. }
  272. bool is_timed_out() const { return m_timed_out; }
  273. private:
  274. virtual void visit_edges(JS::Cell::Visitor& visitor) override
  275. {
  276. Base::visit_edges(visitor);
  277. visitor.visit(m_on_timeout);
  278. }
  279. NonnullRefPtr<Core::Timer> m_timer;
  280. JS::GCPtr<OnScriptComplete> m_on_timeout;
  281. bool m_timed_out { false };
  282. };
  283. JS_DEFINE_ALLOCATOR(HeapTimer);
  284. void execute_script(HTML::BrowsingContext const& browsing_context, ByteString body, JS::MarkedVector<JS::Value> arguments, Optional<u64> const& timeout_ms, JS::NonnullGCPtr<OnScriptComplete> on_complete)
  285. {
  286. auto const* document = browsing_context.active_document();
  287. auto& realm = document->realm();
  288. auto& vm = document->vm();
  289. // 5. Let timer be a new timer.
  290. auto timer = vm.heap().allocate<HeapTimer>(realm);
  291. // 6. If timeout is not null:
  292. if (timeout_ms.has_value()) {
  293. // 1. Start the timer with timer and timeout.
  294. timer->start(timeout_ms.value(), on_complete);
  295. }
  296. // AD-HOC: An execution context is required for Promise creation hooks.
  297. HTML::TemporaryExecutionContext execution_context { document->relevant_settings_object(), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
  298. // 7. Let promise be a new Promise.
  299. auto promise_capability = WebIDL::create_promise(realm);
  300. JS::NonnullGCPtr promise { verify_cast<JS::Promise>(*promise_capability->promise()) };
  301. // 8. Run the following substeps in parallel:
  302. Platform::EventLoopPlugin::the().deferred_invoke([&realm, &browsing_context, promise_capability, document, promise, body = move(body), arguments = move(arguments)]() mutable {
  303. HTML::TemporaryExecutionContext execution_context { document->relevant_settings_object() };
  304. // 1. Let scriptPromise be the result of promise-calling execute a function body, with arguments body and arguments.
  305. auto script_result = execute_a_function_body(browsing_context, body, move(arguments));
  306. // 2. Upon fulfillment of scriptPromise with value v, resolve promise with value v.
  307. if (script_result.has_value()) {
  308. WebIDL::resolve_promise(realm, promise_capability, script_result.release_value());
  309. }
  310. // 3. Upon rejection of scriptPromise with value r, reject promise with value r.
  311. if (script_result.is_throw_completion()) {
  312. promise->reject(*script_result.throw_completion().value());
  313. }
  314. });
  315. // 9. Wait until promise is resolved, or timer's timeout fired flag is set, whichever occurs first.
  316. auto reaction_steps = JS::create_heap_function(vm.heap(), [&realm, promise, timer, on_complete](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  317. if (timer->is_timed_out())
  318. return JS::js_undefined();
  319. timer->stop();
  320. auto json_value_or_error = json_clone(realm, promise->result());
  321. if (json_value_or_error.is_error()) {
  322. auto error_object = JsonObject {};
  323. error_object.set("name", "Error");
  324. error_object.set("message", "Could not clone result value");
  325. on_complete->function()({ ExecuteScriptResultType::JavaScriptError, move(error_object) });
  326. }
  327. // 10. If promise is still pending and timer's timeout fired flag is set, return error with error code script timeout.
  328. // NOTE: This is handled by the HeapTimer.
  329. // 11. If promise is fulfilled with value v, let result be JSON clone with session and v, and return success with data result.
  330. else if (promise->state() == JS::Promise::State::Fulfilled) {
  331. on_complete->function()({ ExecuteScriptResultType::PromiseResolved, json_value_or_error.release_value() });
  332. }
  333. // 12. If promise is rejected with reason r, let result be JSON clone with session and r, and return error with error code javascript error and data result.
  334. else if (promise->state() == JS::Promise::State::Rejected) {
  335. on_complete->function()({ ExecuteScriptResultType::PromiseRejected, json_value_or_error.release_value() });
  336. }
  337. return JS::js_undefined();
  338. });
  339. WebIDL::react_to_promise(promise_capability, reaction_steps, reaction_steps);
  340. }
  341. void execute_async_script(HTML::BrowsingContext const& browsing_context, ByteString body, JS::MarkedVector<JS::Value> arguments, Optional<u64> const& timeout_ms, JS::NonnullGCPtr<OnScriptComplete> on_complete)
  342. {
  343. auto const* document = browsing_context.active_document();
  344. auto& realm = document->realm();
  345. auto& vm = document->vm();
  346. // 5. Let timer be a new timer.
  347. auto timer = vm.heap().allocate<HeapTimer>(realm);
  348. // 6. If timeout is not null:
  349. if (timeout_ms.has_value()) {
  350. // 1. Start the timer with timer and timeout.
  351. timer->start(timeout_ms.value(), on_complete);
  352. }
  353. // AD-HOC: An execution context is required for Promise creation hooks.
  354. HTML::TemporaryExecutionContext execution_context { document->relevant_settings_object(), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
  355. // 7. Let promise be a new Promise.
  356. auto promise_capability = WebIDL::create_promise(realm);
  357. JS::NonnullGCPtr promise { verify_cast<JS::Promise>(*promise_capability->promise()) };
  358. // 8. Run the following substeps in parallel:
  359. Platform::EventLoopPlugin::the().deferred_invoke([&vm, &realm, &browsing_context, timer, document, promise_capability, promise, body = move(body), arguments = move(arguments)]() mutable {
  360. HTML::TemporaryExecutionContext execution_context { document->relevant_settings_object() };
  361. // 1. Let resolvingFunctions be CreateResolvingFunctions(promise).
  362. auto resolving_functions = promise->create_resolving_functions();
  363. // 2. Append resolvingFunctions.[[Resolve]] to arguments.
  364. arguments.append(resolving_functions.resolve);
  365. // 3. Let result be the result of calling execute a function body, with arguments body and arguments.
  366. // FIXME: 'result' -> 'scriptResult' (spec issue)
  367. auto script_result = execute_a_function_body(browsing_context, body, move(arguments));
  368. // 4. If scriptResult.[[Type]] is not normal, then reject promise with value scriptResult.[[Value]], and abort these steps.
  369. // NOTE: Prior revisions of this specification did not recognize the return value of the provided script.
  370. // In order to preserve legacy behavior, the return value only influences the command if it is a
  371. // "thenable" object or if determining this produces an exception.
  372. if (script_result.is_throw_completion()) {
  373. promise->reject(*script_result.throw_completion().value());
  374. return;
  375. }
  376. // 5. If Type(scriptResult.[[Value]]) is not Object, then abort these steps.
  377. if (!script_result.value().is_object())
  378. return;
  379. // 6. Let then be Get(scriptResult.[[Value]], "then").
  380. auto then = script_result.value().as_object().get(vm.names.then);
  381. // 7. If then.[[Type]] is not normal, then reject promise with value then.[[Value]], and abort these steps.
  382. if (then.is_throw_completion()) {
  383. promise->reject(*then.throw_completion().value());
  384. return;
  385. }
  386. // 8. If IsCallable(then.[[Type]]) is false, then abort these steps.
  387. if (!then.value().is_function())
  388. return;
  389. // 9. Let scriptPromise be PromiseResolve(Promise, scriptResult.[[Value]]).
  390. auto script_promise_or_error = JS::promise_resolve(vm, realm.intrinsics().promise_constructor(), script_result.value());
  391. if (script_promise_or_error.is_throw_completion())
  392. return;
  393. auto& script_promise = static_cast<JS::Promise&>(*script_promise_or_error.value());
  394. vm.custom_data()->spin_event_loop_until([&] {
  395. return timer->is_timed_out() || script_promise.state() != JS::Promise::State::Pending;
  396. });
  397. // 10. Upon fulfillment of scriptPromise with value v, resolve promise with value v.
  398. if (script_promise.state() == JS::Promise::State::Fulfilled)
  399. WebIDL::resolve_promise(realm, promise_capability, script_promise.result());
  400. // 11. Upon rejection of scriptPromise with value r, reject promise with value r.
  401. if (script_promise.state() == JS::Promise::State::Rejected)
  402. WebIDL::reject_promise(realm, promise_capability, script_promise.result());
  403. });
  404. // 9. Wait until promise is resolved, or timer's timeout fired flag is set, whichever occurs first.
  405. auto reaction_steps = JS::create_heap_function(vm.heap(), [&realm, promise, timer, on_complete](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  406. if (timer->is_timed_out())
  407. return JS::js_undefined();
  408. timer->stop();
  409. auto json_value_or_error = json_clone(realm, promise->result());
  410. if (json_value_or_error.is_error()) {
  411. auto error_object = JsonObject {};
  412. error_object.set("name", "Error");
  413. error_object.set("message", "Could not clone result value");
  414. on_complete->function()({ ExecuteScriptResultType::JavaScriptError, move(error_object) });
  415. }
  416. // 10. If promise is still pending and timer's timeout fired flag is set, return error with error code script timeout.
  417. // NOTE: This is handled by the HeapTimer.
  418. // 11. If promise is fulfilled with value v, let result be JSON clone with session and v, and return success with data result.
  419. else if (promise->state() == JS::Promise::State::Fulfilled) {
  420. on_complete->function()({ ExecuteScriptResultType::PromiseResolved, json_value_or_error.release_value() });
  421. }
  422. // 12. If promise is rejected with reason r, let result be JSON clone with session and r, and return error with error code javascript error and data result.
  423. else if (promise->state() == JS::Promise::State::Rejected) {
  424. on_complete->function()({ ExecuteScriptResultType::PromiseRejected, json_value_or_error.release_value() });
  425. }
  426. return JS::js_undefined();
  427. });
  428. WebIDL::react_to_promise(promise_capability, reaction_steps, reaction_steps);
  429. }
  430. }