MainThreadVM.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. /*
  2. * Copyright (c) 2021-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2023, Luke Wilde <lukew@serenityos.org>
  4. * Copyright (c) 2022, networkException <networkexception@serenityos.org>
  5. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <LibJS/Heap/DeferGC.h>
  10. #include <LibJS/Module.h>
  11. #include <LibJS/Runtime/Array.h>
  12. #include <LibJS/Runtime/Environment.h>
  13. #include <LibJS/Runtime/FinalizationRegistry.h>
  14. #include <LibJS/Runtime/ModuleRequest.h>
  15. #include <LibJS/Runtime/NativeFunction.h>
  16. #include <LibJS/Runtime/VM.h>
  17. #include <LibWeb/Bindings/Intrinsics.h>
  18. #include <LibWeb/Bindings/MainThreadVM.h>
  19. #include <LibWeb/Bindings/WindowExposedInterfaces.h>
  20. #include <LibWeb/DOM/Document.h>
  21. #include <LibWeb/DOM/MutationType.h>
  22. #include <LibWeb/HTML/AttributeNames.h>
  23. #include <LibWeb/HTML/CustomElements/CustomElementDefinition.h>
  24. #include <LibWeb/HTML/CustomElements/CustomElementReactionNames.h>
  25. #include <LibWeb/HTML/EventNames.h>
  26. #include <LibWeb/HTML/Location.h>
  27. #include <LibWeb/HTML/PromiseRejectionEvent.h>
  28. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  29. #include <LibWeb/HTML/Scripting/Environments.h>
  30. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  31. #include <LibWeb/HTML/Scripting/Fetching.h>
  32. #include <LibWeb/HTML/TagNames.h>
  33. #include <LibWeb/HTML/Window.h>
  34. #include <LibWeb/HTML/WindowProxy.h>
  35. #include <LibWeb/Namespace.h>
  36. #include <LibWeb/NavigationTiming/EntryNames.h>
  37. #include <LibWeb/PerformanceTimeline/EntryTypes.h>
  38. #include <LibWeb/Platform/EventLoopPlugin.h>
  39. #include <LibWeb/SVG/AttributeNames.h>
  40. #include <LibWeb/SVG/TagNames.h>
  41. #include <LibWeb/UIEvents/EventNames.h>
  42. #include <LibWeb/WebGL/EventNames.h>
  43. #include <LibWeb/WebIDL/AbstractOperations.h>
  44. #include <LibWeb/XHR/EventNames.h>
  45. namespace Web::Bindings {
  46. static RefPtr<JS::VM> s_main_thread_vm;
  47. // https://html.spec.whatwg.org/multipage/webappapis.html#active-script
  48. HTML::Script* active_script()
  49. {
  50. // 1. Let record be GetActiveScriptOrModule().
  51. auto record = main_thread_vm().get_active_script_or_module();
  52. // 2. If record is null, return null.
  53. // 3. Return record.[[HostDefined]].
  54. return record.visit(
  55. [](JS::NonnullGCPtr<JS::Script>& js_script) -> HTML::Script* {
  56. return verify_cast<HTML::ClassicScript>(js_script->host_defined());
  57. },
  58. [](JS::NonnullGCPtr<JS::Module>& js_module) -> HTML::Script* {
  59. return verify_cast<HTML::ModuleScript>(js_module->host_defined());
  60. },
  61. [](Empty) -> HTML::Script* {
  62. return nullptr;
  63. });
  64. }
  65. ErrorOr<void> initialize_main_thread_vm()
  66. {
  67. VERIFY(!s_main_thread_vm);
  68. s_main_thread_vm = TRY(JS::VM::create(make<WebEngineCustomData>()));
  69. // NOTE: We intentionally leak the main thread JavaScript VM.
  70. // This avoids doing an exhaustive garbage collection on process exit.
  71. s_main_thread_vm->ref();
  72. // These strings could potentially live on the VM similar to CommonPropertyNames.
  73. TRY(DOM::MutationType::initialize_strings());
  74. TRY(HTML::AttributeNames::initialize_strings());
  75. TRY(HTML::CustomElementReactionNames::initialize_strings());
  76. TRY(HTML::EventNames::initialize_strings());
  77. TRY(HTML::TagNames::initialize_strings());
  78. TRY(Namespace::initialize_strings());
  79. TRY(NavigationTiming::EntryNames::initialize_strings());
  80. TRY(PerformanceTimeline::EntryTypes::initialize_strings());
  81. TRY(SVG::AttributeNames::initialize_strings());
  82. TRY(SVG::TagNames::initialize_strings());
  83. TRY(UIEvents::EventNames::initialize_strings());
  84. TRY(WebGL::EventNames::initialize_strings());
  85. TRY(XHR::EventNames::initialize_strings());
  86. static_cast<WebEngineCustomData*>(s_main_thread_vm->custom_data())->event_loop.set_vm(*s_main_thread_vm);
  87. // 8.1.5.1 HostEnsureCanAddPrivateElement(O), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostensurecanaddprivateelement-implementation
  88. s_main_thread_vm->host_ensure_can_add_private_element = [](JS::Object const& object) -> JS::ThrowCompletionOr<void> {
  89. // 1. If O is a WindowProxy object, or implements Location, then return Completion { [[Type]]: throw, [[Value]]: a new TypeError }.
  90. if (is<HTML::WindowProxy>(object) || is<HTML::Location>(object))
  91. return s_main_thread_vm->throw_completion<JS::TypeError>("Cannot add private elements to window or location object"sv);
  92. // 2. Return NormalCompletion(unused).
  93. return {};
  94. };
  95. // FIXME: Implement 8.1.5.2 HostEnsureCanCompileStrings(callerRealm, calleeRealm), https://html.spec.whatwg.org/multipage/webappapis.html#hostensurecancompilestrings(callerrealm,-calleerealm)
  96. // 8.1.5.3 HostPromiseRejectionTracker(promise, operation), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostpromiserejectiontracker-implementation
  97. s_main_thread_vm->host_promise_rejection_tracker = [](JS::Promise& promise, JS::Promise::RejectionOperation operation) {
  98. // 1. Let script be the running script.
  99. // The running script is the script in the [[HostDefined]] field in the ScriptOrModule component of the running JavaScript execution context.
  100. HTML::Script* script { nullptr };
  101. s_main_thread_vm->running_execution_context().script_or_module.visit(
  102. [&script](JS::NonnullGCPtr<JS::Script>& js_script) {
  103. script = verify_cast<HTML::ClassicScript>(js_script->host_defined());
  104. },
  105. [&script](JS::NonnullGCPtr<JS::Module>& js_module) {
  106. script = verify_cast<HTML::ModuleScript>(js_module->host_defined());
  107. },
  108. [](Empty) {
  109. });
  110. // 2. If script is a classic script and script's muted errors is true, then return.
  111. // NOTE: is<T>() returns false if nullptr is passed.
  112. if (is<HTML::ClassicScript>(script)) {
  113. auto const& classic_script = static_cast<HTML::ClassicScript const&>(*script);
  114. if (classic_script.muted_errors() == HTML::ClassicScript::MutedErrors::Yes)
  115. return;
  116. }
  117. // 3. Let settings object be the current settings object.
  118. // 4. If script is not null, then set settings object to script's settings object.
  119. auto& settings_object = script ? script->settings_object() : HTML::current_settings_object();
  120. switch (operation) {
  121. case JS::Promise::RejectionOperation::Reject:
  122. // 4. If operation is "reject",
  123. // 1. Add promise to settings object's about-to-be-notified rejected promises list.
  124. settings_object.push_onto_about_to_be_notified_rejected_promises_list(promise);
  125. break;
  126. case JS::Promise::RejectionOperation::Handle: {
  127. // 5. If operation is "handle",
  128. // 1. If settings object's about-to-be-notified rejected promises list contains promise, then remove promise from that list and return.
  129. bool removed_about_to_be_notified_rejected_promise = settings_object.remove_from_about_to_be_notified_rejected_promises_list(promise);
  130. if (removed_about_to_be_notified_rejected_promise)
  131. return;
  132. // 3. Remove promise from settings object's outstanding rejected promises weak set.
  133. bool removed_outstanding_rejected_promise = settings_object.remove_from_outstanding_rejected_promises_weak_set(&promise);
  134. // 2. If settings object's outstanding rejected promises weak set does not contain promise, then return.
  135. // NOTE: This is done out of order because removed_outstanding_rejected_promise will be false if the promise wasn't in the set or true if it was and got removed.
  136. if (!removed_outstanding_rejected_promise)
  137. return;
  138. // 4. Let global be settings object's global object.
  139. auto& global = settings_object.global_object();
  140. // 5. Queue a global task on the DOM manipulation task source given global to fire an event named rejectionhandled at global, using PromiseRejectionEvent,
  141. // with the promise attribute initialized to promise, and the reason attribute initialized to the value of promise's [[PromiseResult]] internal slot.
  142. HTML::queue_global_task(HTML::Task::Source::DOMManipulation, global, [&global, &promise] {
  143. // FIXME: This currently assumes that global is a WindowObject.
  144. auto& window = verify_cast<HTML::Window>(global);
  145. HTML::PromiseRejectionEventInit event_init {
  146. {}, // Initialize the inherited DOM::EventInit
  147. /* .promise = */ promise,
  148. /* .reason = */ promise.result(),
  149. };
  150. auto promise_rejection_event = HTML::PromiseRejectionEvent::create(HTML::relevant_realm(global), HTML::EventNames::rejectionhandled, event_init).release_value_but_fixme_should_propagate_errors();
  151. window.dispatch_event(promise_rejection_event);
  152. });
  153. break;
  154. }
  155. default:
  156. VERIFY_NOT_REACHED();
  157. }
  158. };
  159. // 8.1.5.4.1 HostCallJobCallback(callback, V, argumentsList), https://html.spec.whatwg.org/multipage/webappapis.html#hostcalljobcallback
  160. s_main_thread_vm->host_call_job_callback = [](JS::JobCallback& callback, JS::Value this_value, JS::MarkedVector<JS::Value> arguments_list) {
  161. auto& callback_host_defined = verify_cast<WebEngineCustomJobCallbackData>(*callback.custom_data);
  162. // 1. Let incumbent settings be callback.[[HostDefined]].[[IncumbentSettings]]. (NOTE: Not necessary)
  163. // 2. Let script execution context be callback.[[HostDefined]].[[ActiveScriptContext]]. (NOTE: Not necessary)
  164. // 3. Prepare to run a callback with incumbent settings.
  165. callback_host_defined.incumbent_settings->prepare_to_run_callback();
  166. // 4. If script execution context is not null, then push script execution context onto the JavaScript execution context stack.
  167. if (callback_host_defined.active_script_context)
  168. s_main_thread_vm->push_execution_context(*callback_host_defined.active_script_context);
  169. // 5. Let result be Call(callback.[[Callback]], V, argumentsList).
  170. auto result = JS::call(*s_main_thread_vm, *callback.callback.cell(), this_value, move(arguments_list));
  171. // 6. If script execution context is not null, then pop script execution context from the JavaScript execution context stack.
  172. if (callback_host_defined.active_script_context) {
  173. VERIFY(&s_main_thread_vm->running_execution_context() == callback_host_defined.active_script_context.ptr());
  174. s_main_thread_vm->pop_execution_context();
  175. }
  176. // 7. Clean up after running a callback with incumbent settings.
  177. callback_host_defined.incumbent_settings->clean_up_after_running_callback();
  178. // 8. Return result.
  179. return result;
  180. };
  181. // 8.1.5.4.2 HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuefinalizationregistrycleanupjob
  182. s_main_thread_vm->host_enqueue_finalization_registry_cleanup_job = [](JS::FinalizationRegistry& finalization_registry) {
  183. // 1. Let global be finalizationRegistry.[[Realm]]'s global object.
  184. auto& global = finalization_registry.realm().global_object();
  185. // 2. Queue a global task on the JavaScript engine task source given global to perform the following steps:
  186. HTML::queue_global_task(HTML::Task::Source::JavaScriptEngine, global, [&finalization_registry] {
  187. // 1. Let entry be finalizationRegistry.[[CleanupCallback]].[[Callback]].[[Realm]]'s environment settings object.
  188. auto& entry = host_defined_environment_settings_object(*finalization_registry.cleanup_callback().callback.cell()->realm());
  189. // 2. Check if we can run script with entry. If this returns "do not run", then return.
  190. if (entry.can_run_script() == HTML::RunScriptDecision::DoNotRun)
  191. return;
  192. // 3. Prepare to run script with entry.
  193. entry.prepare_to_run_script();
  194. // 4. Let result be the result of performing CleanupFinalizationRegistry(finalizationRegistry).
  195. auto result = finalization_registry.cleanup();
  196. // 5. Clean up after running script with entry.
  197. entry.clean_up_after_running_script();
  198. // 6. If result is an abrupt completion, then report the exception given by result.[[Value]].
  199. if (result.is_error())
  200. HTML::report_exception(result, finalization_registry.realm());
  201. });
  202. };
  203. // 8.1.5.4.3 HostEnqueuePromiseJob(job, realm), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuepromisejob
  204. s_main_thread_vm->host_enqueue_promise_job = [](Function<JS::ThrowCompletionOr<JS::Value>()> job, JS::Realm* realm) {
  205. // 1. If realm is not null, then let job settings be the settings object for realm. Otherwise, let job settings be null.
  206. HTML::EnvironmentSettingsObject* job_settings { nullptr };
  207. if (realm)
  208. job_settings = &host_defined_environment_settings_object(*realm);
  209. // IMPLEMENTATION DEFINED: The JS spec says we must take implementation defined steps to make the currently active script or module at the time of HostEnqueuePromiseJob being invoked
  210. // also be the active script or module of the job at the time of its invocation.
  211. // This means taking it here now and passing it through to the lambda.
  212. auto script_or_module = s_main_thread_vm->get_active_script_or_module();
  213. // 2. Queue a microtask on the surrounding agent's event loop to perform the following steps:
  214. // This instance of "queue a microtask" uses the "implied document". The best fit for "implied document" here is "If the task is being queued by or for a script, then return the script's settings object's responsible document."
  215. // Do note that "implied document" from the spec is handwavy and the spec authors are trying to get rid of it: https://github.com/whatwg/html/issues/4980
  216. auto* script = active_script();
  217. // NOTE: This keeps job_settings alive by keeping realm alive, which is holding onto job_settings.
  218. HTML::queue_a_microtask(script ? script->settings_object().responsible_document().ptr() : nullptr, [job_settings, job = move(job), script_or_module = move(script_or_module)] {
  219. // The dummy execution context has to be kept up here to keep it alive for the duration of the function.
  220. Optional<JS::ExecutionContext> dummy_execution_context;
  221. if (job_settings) {
  222. // 1. If job settings is not null, then check if we can run script with job settings. If this returns "do not run" then return.
  223. if (job_settings->can_run_script() == HTML::RunScriptDecision::DoNotRun)
  224. return;
  225. // 2. If job settings is not null, then prepare to run script with job settings.
  226. job_settings->prepare_to_run_script();
  227. // IMPLEMENTATION DEFINED: Additionally to preparing to run a script, we also prepare to run a callback here. This matches WebIDL's
  228. // invoke_callback() / call_user_object_operation() functions, and prevents a crash in host_make_job_callback()
  229. // when getting the incumbent settings object.
  230. job_settings->prepare_to_run_callback();
  231. // IMPLEMENTATION DEFINED: Per the previous "implementation defined" comment, we must now make the script or module the active script or module.
  232. // Since the only active execution context currently is the realm execution context of job settings, lets attach it here.
  233. job_settings->realm_execution_context().script_or_module = script_or_module;
  234. } else {
  235. // FIXME: We need to setup a dummy execution context in case a JS::NativeFunction is called when processing the job.
  236. // This is because JS::NativeFunction::call excepts something to be on the execution context stack to be able to get the caller context to initialize the environment.
  237. // Do note that the JS spec gives _no_ guarantee that the execution context stack has something on it if HostEnqueuePromiseJob was called with a null realm: https://tc39.es/ecma262/#job-preparedtoevaluatecode
  238. dummy_execution_context = JS::ExecutionContext { s_main_thread_vm->heap() };
  239. dummy_execution_context->script_or_module = script_or_module;
  240. s_main_thread_vm->push_execution_context(dummy_execution_context.value());
  241. }
  242. // 3. Let result be job().
  243. [[maybe_unused]] auto result = job();
  244. // 4. If job settings is not null, then clean up after running script with job settings.
  245. if (job_settings) {
  246. // IMPLEMENTATION DEFINED: Disassociate the realm execution context from the script or module.
  247. job_settings->realm_execution_context().script_or_module = Empty {};
  248. // IMPLEMENTATION DEFINED: See comment above, we need to clean up the non-standard prepare_to_run_callback() call.
  249. job_settings->clean_up_after_running_callback();
  250. job_settings->clean_up_after_running_script();
  251. } else {
  252. // Pop off the dummy execution context. See the above FIXME block about why this is done.
  253. s_main_thread_vm->pop_execution_context();
  254. }
  255. // 5. If result is an abrupt completion, then report the exception given by result.[[Value]].
  256. if (result.is_error())
  257. HTML::report_exception(result, job_settings->realm());
  258. });
  259. };
  260. // 8.1.5.4.4 HostMakeJobCallback(callable), https://html.spec.whatwg.org/multipage/webappapis.html#hostmakejobcallback
  261. s_main_thread_vm->host_make_job_callback = [](JS::FunctionObject& callable) -> JS::JobCallback {
  262. // 1. Let incumbent settings be the incumbent settings object.
  263. auto& incumbent_settings = HTML::incumbent_settings_object();
  264. // 2. Let active script be the active script.
  265. auto* script = active_script();
  266. // 3. Let script execution context be null.
  267. OwnPtr<JS::ExecutionContext> script_execution_context;
  268. // 4. If active script is not null, set script execution context to a new JavaScript execution context, with its Function field set to null,
  269. // its Realm field set to active script's settings object's Realm, and its ScriptOrModule set to active script's record.
  270. if (script) {
  271. script_execution_context = adopt_own(*new JS::ExecutionContext(s_main_thread_vm->heap()));
  272. script_execution_context->function = nullptr;
  273. script_execution_context->realm = &script->settings_object().realm();
  274. if (is<HTML::ClassicScript>(script)) {
  275. script_execution_context->script_or_module = JS::NonnullGCPtr<JS::Script>(*verify_cast<HTML::ClassicScript>(script)->script_record());
  276. } else if (is<HTML::ModuleScript>(script)) {
  277. if (is<HTML::JavaScriptModuleScript>(script)) {
  278. script_execution_context->script_or_module = JS::NonnullGCPtr<JS::Module>(*verify_cast<HTML::JavaScriptModuleScript>(script)->record());
  279. } else {
  280. // NOTE: Handle CSS and JSON module scripts once we have those.
  281. VERIFY_NOT_REACHED();
  282. }
  283. } else {
  284. VERIFY_NOT_REACHED();
  285. }
  286. }
  287. // 5. Return the JobCallback Record { [[Callback]]: callable, [[HostDefined]]: { [[IncumbentSettings]]: incumbent settings, [[ActiveScriptContext]]: script execution context } }.
  288. auto host_defined = adopt_own(*new WebEngineCustomJobCallbackData(incumbent_settings, move(script_execution_context)));
  289. return { JS::make_handle(&callable), move(host_defined) };
  290. };
  291. // FIXME: Implement 8.1.5.5.1 HostGetImportMetaProperties(moduleRecord), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetimportmetaproperties
  292. // FIXME: Implement 8.1.5.5.2 HostImportModuleDynamically(referencingScriptOrModule, moduleRequest, promiseCapability), https://html.spec.whatwg.org/multipage/webappapis.html#hostimportmoduledynamically(referencingscriptormodule,-modulerequest,-promisecapability)
  293. // FIXME: Implement 8.1.5.5.3 HostResolveImportedModule(referencingScriptOrModule, moduleRequest), https://html.spec.whatwg.org/multipage/webappapis.html#hostresolveimportedmodule(referencingscriptormodule,-modulerequest)
  294. // 8.1.5.5.4 HostGetSupportedImportAssertions(), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetsupportedimportassertions
  295. s_main_thread_vm->host_get_supported_import_assertions = []() -> Vector<DeprecatedString> {
  296. // 1. Return « "type" ».
  297. return { "type"sv };
  298. };
  299. // 8.1.6.5.3 HostResolveImportedModule(referencingScriptOrModule, moduleRequest), https://html.spec.whatwg.org/multipage/webappapis.html#hostresolveimportedmodule(referencingscriptormodule,-modulerequest)
  300. s_main_thread_vm->host_resolve_imported_module = [](JS::ScriptOrModule const& referencing_string_or_module, JS::ModuleRequest const& module_request) -> JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Module>> {
  301. // 1. Let moduleMap and referencingScript be null.
  302. Optional<HTML::ModuleMap&> module_map;
  303. Optional<HTML::Script&> referencing_script;
  304. // 2. If referencingScriptOrModule is not null, then:
  305. if (!referencing_string_or_module.has<Empty>()) {
  306. // 1. Set referencingScript to referencingScriptOrModule.[[HostDefined]].
  307. referencing_script = verify_cast<HTML::Script>(referencing_string_or_module.has<JS::NonnullGCPtr<JS::Script>>() ? *referencing_string_or_module.get<JS::NonnullGCPtr<JS::Script>>()->host_defined() : *referencing_string_or_module.get<JS::NonnullGCPtr<JS::Module>>()->host_defined());
  308. // 2. Set moduleMap to referencingScript's settings object's module map.
  309. module_map = referencing_script->settings_object().module_map();
  310. }
  311. // 3. Otherwise:
  312. else {
  313. // 1. Assert: there is a current settings object.
  314. // NOTE: This is handled by the HTML::current_settings_object() accessor.
  315. // 2. Set moduleMap to the current settings object's module map.
  316. module_map = HTML::current_settings_object().module_map();
  317. }
  318. // 4. Let url be the result of resolving a module specifier given referencingScript and moduleRequest.[[Specifier]].
  319. auto url = MUST(HTML::resolve_module_specifier(referencing_script, module_request.module_specifier));
  320. // 5. Assert: the previous step never throws an exception, because resolving a module specifier must have been previously successful
  321. // with these same two arguments (either while creating the corresponding module script, or in fetch an import() module script graph).
  322. // NOTE: Handled by MUST above.
  323. // 6. Let moduleType be the result of running the module type from module request steps given moduleRequest.
  324. auto module_type = HTML::module_type_from_module_request(module_request);
  325. // 7. Let resolvedModuleScript be moduleMap[(url, moduleType)]. (This entry must exist for us to have gotten to this point.)
  326. auto resolved_module_script = module_map->get(url, module_type).value();
  327. // 8. Assert: resolvedModuleScript is a module script (i.e., is not null or "fetching").
  328. VERIFY(resolved_module_script.type == HTML::ModuleMap::EntryType::ModuleScript);
  329. // 9. Assert: resolvedModuleScript's record is not null.
  330. VERIFY(resolved_module_script.module_script->record());
  331. // 10. Return resolvedModuleScript's record.
  332. return JS::NonnullGCPtr(*resolved_module_script.module_script->record());
  333. };
  334. return {};
  335. }
  336. JS::VM& main_thread_vm()
  337. {
  338. VERIFY(s_main_thread_vm);
  339. return *s_main_thread_vm;
  340. }
  341. // https://dom.spec.whatwg.org/#queue-a-mutation-observer-compound-microtask
  342. void queue_mutation_observer_microtask(DOM::Document const& document)
  343. {
  344. auto& vm = main_thread_vm();
  345. auto& custom_data = verify_cast<WebEngineCustomData>(*vm.custom_data());
  346. // 1. If the surrounding agent’s mutation observer microtask queued is true, then return.
  347. if (custom_data.mutation_observer_microtask_queued)
  348. return;
  349. // 2. Set the surrounding agent’s mutation observer microtask queued to true.
  350. custom_data.mutation_observer_microtask_queued = true;
  351. // 3. Queue a microtask to notify mutation observers.
  352. // NOTE: This uses the implied document concept. In the case of mutation observers, it is always done in a node context, so document should be that node's document.
  353. // FIXME: Is it safe to pass custom_data through?
  354. HTML::queue_a_microtask(&document, [&custom_data]() {
  355. // 1. Set the surrounding agent’s mutation observer microtask queued to false.
  356. custom_data.mutation_observer_microtask_queued = false;
  357. // 2. Let notifySet be a clone of the surrounding agent’s mutation observers.
  358. auto notify_set = custom_data.mutation_observers;
  359. // FIXME: 3. Let signalSet be a clone of the surrounding agent’s signal slots.
  360. // FIXME: 4. Empty the surrounding agent’s signal slots.
  361. // 5. For each mo of notifySet:
  362. for (auto& mutation_observer : notify_set) {
  363. // 1. Let records be a clone of mo’s record queue.
  364. // 2. Empty mo’s record queue.
  365. auto records = mutation_observer->take_records();
  366. // 3. For each node of mo’s node list, remove all transient registered observers whose observer is mo from node’s registered observer list.
  367. for (auto& node : mutation_observer->node_list()) {
  368. // FIXME: Is this correct?
  369. if (node.is_null())
  370. continue;
  371. node->registered_observers_list().remove_all_matching([&mutation_observer](DOM::RegisteredObserver& registered_observer) {
  372. return is<DOM::TransientRegisteredObserver>(registered_observer) && static_cast<DOM::TransientRegisteredObserver&>(registered_observer).observer().ptr() == mutation_observer.ptr();
  373. });
  374. }
  375. // 4. If records is not empty, then invoke mo’s callback with « records, mo », and mo. If this throws an exception, catch it, and report the exception.
  376. if (!records.is_empty()) {
  377. auto& callback = mutation_observer->callback();
  378. auto& realm = callback.callback_context->realm();
  379. auto wrapped_records = MUST(JS::Array::create(realm, 0));
  380. for (size_t i = 0; i < records.size(); ++i) {
  381. auto& record = records.at(i);
  382. auto property_index = JS::PropertyKey { i };
  383. MUST(wrapped_records->create_data_property(property_index, record.ptr()));
  384. }
  385. auto result = WebIDL::invoke_callback(callback, mutation_observer.ptr(), wrapped_records, mutation_observer.ptr());
  386. if (result.is_abrupt())
  387. HTML::report_exception(result, realm);
  388. }
  389. }
  390. // FIXME: 6. For each slot of signalSet, fire an event named slotchange, with its bubbles attribute set to true, at slot.
  391. });
  392. }
  393. // https://html.spec.whatwg.org/multipage/webappapis.html#creating-a-new-javascript-realm
  394. NonnullOwnPtr<JS::ExecutionContext> create_a_new_javascript_realm(JS::VM& vm, Function<JS::Object*(JS::Realm&)> create_global_object, Function<JS::Object*(JS::Realm&)> create_global_this_value)
  395. {
  396. // 1. Perform InitializeHostDefinedRealm() with the provided customizations for creating the global object and the global this binding.
  397. // 2. Let realm execution context be the running JavaScript execution context.
  398. auto realm_execution_context = MUST(JS::Realm::initialize_host_defined_realm(vm, move(create_global_object), move(create_global_this_value)));
  399. // 3. Remove realm execution context from the JavaScript execution context stack.
  400. vm.execution_context_stack().remove_first_matching([&realm_execution_context](auto execution_context) {
  401. return execution_context == realm_execution_context.ptr();
  402. });
  403. // NO-OP: 4. Let realm be realm execution context's Realm component.
  404. // NO-OP: 5. Set realm's agent to agent.
  405. // FIXME: 6. If agent's agent cluster's cross-origin isolation mode is "none", then:
  406. // 1. Let global be realm's global object.
  407. // 2. Let status be ! global.[[Delete]]("SharedArrayBuffer").
  408. // 3. Assert: status is true.
  409. // 7. Return realm execution context.
  410. return realm_execution_context;
  411. }
  412. void WebEngineCustomData::spin_event_loop_until(Function<bool()> goal_condition)
  413. {
  414. Platform::EventLoopPlugin::the().spin_until(move(goal_condition));
  415. }
  416. // https://html.spec.whatwg.org/multipage/custom-elements.html#invoke-custom-element-reactions
  417. void invoke_custom_element_reactions(Vector<JS::Handle<DOM::Element>>& element_queue)
  418. {
  419. // 1. While queue is not empty:
  420. while (!element_queue.is_empty()) {
  421. // 1. Let element be the result of dequeuing from queue.
  422. auto element = element_queue.take_first();
  423. // 2. Let reactions be element's custom element reaction queue.
  424. auto& reactions = element->custom_element_reaction_queue();
  425. // 3. Repeat until reactions is empty:
  426. while (!reactions.is_empty()) {
  427. // 1. Remove the first element of reactions, and let reaction be that element. Switch on reaction's type:
  428. auto reaction = reactions.take_first();
  429. auto maybe_exception = reaction.visit(
  430. [&](DOM::CustomElementUpgradeReaction const& custom_element_upgrade_reaction) -> JS::ThrowCompletionOr<void> {
  431. // -> upgrade reaction
  432. // Upgrade element using reaction's custom element definition.
  433. return element->upgrade_element(*custom_element_upgrade_reaction.custom_element_definition);
  434. },
  435. [&](DOM::CustomElementCallbackReaction& custom_element_callback_reaction) -> JS::ThrowCompletionOr<void> {
  436. // -> callback reaction
  437. // Invoke reaction's callback function with reaction's arguments, and with element as the callback this value.
  438. auto result = WebIDL::invoke_callback(*custom_element_callback_reaction.callback, element.ptr(), custom_element_callback_reaction.arguments);
  439. if (result.is_abrupt())
  440. return result.release_error();
  441. return {};
  442. });
  443. // If this throws an exception, catch it, and report the exception.
  444. if (maybe_exception.is_throw_completion())
  445. HTML::report_exception(maybe_exception, element->realm());
  446. }
  447. }
  448. }
  449. }