MainThreadVM.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. /*
  2. * Copyright (c) 2021-2022, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2021-2023, Luke Wilde <lukew@serenityos.org>
  4. * Copyright (c) 2022-2023, 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/AST.h>
  10. #include <LibJS/Heap/DeferGC.h>
  11. #include <LibJS/Module.h>
  12. #include <LibJS/Runtime/Array.h>
  13. #include <LibJS/Runtime/Environment.h>
  14. #include <LibJS/Runtime/FinalizationRegistry.h>
  15. #include <LibJS/Runtime/ModuleRequest.h>
  16. #include <LibJS/Runtime/NativeFunction.h>
  17. #include <LibJS/Runtime/VM.h>
  18. #include <LibJS/SourceTextModule.h>
  19. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  20. #include <LibWeb/Bindings/Intrinsics.h>
  21. #include <LibWeb/Bindings/MainThreadVM.h>
  22. #include <LibWeb/Bindings/WindowExposedInterfaces.h>
  23. #include <LibWeb/DOM/Document.h>
  24. #include <LibWeb/DOM/MutationType.h>
  25. #include <LibWeb/HTML/AttributeNames.h>
  26. #include <LibWeb/HTML/CustomElements/CustomElementDefinition.h>
  27. #include <LibWeb/HTML/CustomElements/CustomElementReactionNames.h>
  28. #include <LibWeb/HTML/EventNames.h>
  29. #include <LibWeb/HTML/Location.h>
  30. #include <LibWeb/HTML/PromiseRejectionEvent.h>
  31. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  32. #include <LibWeb/HTML/Scripting/Environments.h>
  33. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  34. #include <LibWeb/HTML/Scripting/Fetching.h>
  35. #include <LibWeb/HTML/Scripting/ModuleScript.h>
  36. #include <LibWeb/HTML/Scripting/Script.h>
  37. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  38. #include <LibWeb/HTML/TagNames.h>
  39. #include <LibWeb/HTML/Window.h>
  40. #include <LibWeb/HTML/WindowProxy.h>
  41. #include <LibWeb/MathML/TagNames.h>
  42. #include <LibWeb/Namespace.h>
  43. #include <LibWeb/NavigationTiming/EntryNames.h>
  44. #include <LibWeb/PerformanceTimeline/EntryTypes.h>
  45. #include <LibWeb/Platform/EventLoopPlugin.h>
  46. #include <LibWeb/SVG/AttributeNames.h>
  47. #include <LibWeb/SVG/TagNames.h>
  48. #include <LibWeb/UIEvents/EventNames.h>
  49. #include <LibWeb/UIEvents/InputTypes.h>
  50. #include <LibWeb/WebGL/EventNames.h>
  51. #include <LibWeb/WebIDL/AbstractOperations.h>
  52. #include <LibWeb/XHR/EventNames.h>
  53. #include <LibWeb/XLink/AttributeNames.h>
  54. namespace Web::Bindings {
  55. static RefPtr<JS::VM> s_main_thread_vm;
  56. // https://html.spec.whatwg.org/multipage/webappapis.html#active-script
  57. HTML::Script* active_script()
  58. {
  59. // 1. Let record be GetActiveScriptOrModule().
  60. auto record = main_thread_vm().get_active_script_or_module();
  61. // 2. If record is null, return null.
  62. // 3. Return record.[[HostDefined]].
  63. return record.visit(
  64. [](JS::NonnullGCPtr<JS::Script>& js_script) -> HTML::Script* {
  65. return verify_cast<HTML::ClassicScript>(js_script->host_defined());
  66. },
  67. [](JS::NonnullGCPtr<JS::Module>& js_module) -> HTML::Script* {
  68. return verify_cast<HTML::ModuleScript>(js_module->host_defined());
  69. },
  70. [](Empty) -> HTML::Script* {
  71. return nullptr;
  72. });
  73. }
  74. ErrorOr<void> initialize_main_thread_vm(HTML::EventLoop::Type type)
  75. {
  76. VERIFY(!s_main_thread_vm);
  77. s_main_thread_vm = TRY(JS::VM::create(make<WebEngineCustomData>()));
  78. s_main_thread_vm->on_unimplemented_property_access = [](auto const& object, auto const& property_key) {
  79. dbgln("FIXME: Unimplemented IDL interface: '{}.{}'", object.class_name(), property_key.to_string());
  80. };
  81. // NOTE: We intentionally leak the main thread JavaScript VM.
  82. // This avoids doing an exhaustive garbage collection on process exit.
  83. s_main_thread_vm->ref();
  84. auto& custom_data = verify_cast<WebEngineCustomData>(*s_main_thread_vm->custom_data());
  85. custom_data.event_loop = s_main_thread_vm->heap().allocate_without_realm<HTML::EventLoop>(type);
  86. // These strings could potentially live on the VM similar to CommonPropertyNames.
  87. DOM::MutationType::initialize_strings();
  88. HTML::AttributeNames::initialize_strings();
  89. HTML::CustomElementReactionNames::initialize_strings();
  90. HTML::EventNames::initialize_strings();
  91. HTML::TagNames::initialize_strings();
  92. MathML::TagNames::initialize_strings();
  93. Namespace::initialize_strings();
  94. NavigationTiming::EntryNames::initialize_strings();
  95. PerformanceTimeline::EntryTypes::initialize_strings();
  96. SVG::AttributeNames::initialize_strings();
  97. SVG::TagNames::initialize_strings();
  98. UIEvents::EventNames::initialize_strings();
  99. UIEvents::InputTypes::initialize_strings();
  100. WebGL::EventNames::initialize_strings();
  101. XHR::EventNames::initialize_strings();
  102. XLink::AttributeNames::initialize_strings();
  103. // 8.1.5.1 HostEnsureCanAddPrivateElement(O), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostensurecanaddprivateelement-implementation
  104. s_main_thread_vm->host_ensure_can_add_private_element = [](JS::Object const& object) -> JS::ThrowCompletionOr<void> {
  105. // 1. If O is a WindowProxy object, or implements Location, then return Completion { [[Type]]: throw, [[Value]]: a new TypeError }.
  106. if (is<HTML::WindowProxy>(object) || is<HTML::Location>(object))
  107. return s_main_thread_vm->throw_completion<JS::TypeError>("Cannot add private elements to window or location object"sv);
  108. // 2. Return NormalCompletion(unused).
  109. return {};
  110. };
  111. // FIXME: Implement 8.1.5.2 HostEnsureCanCompileStrings(callerRealm, calleeRealm), https://html.spec.whatwg.org/multipage/webappapis.html#hostensurecancompilestrings(callerrealm,-calleerealm)
  112. // 8.1.5.3 HostPromiseRejectionTracker(promise, operation), https://html.spec.whatwg.org/multipage/webappapis.html#the-hostpromiserejectiontracker-implementation
  113. // https://whatpr.org/html/9893/webappapis.html#the-hostpromiserejectiontracker-implementation
  114. s_main_thread_vm->host_promise_rejection_tracker = [](JS::Promise& promise, JS::Promise::RejectionOperation operation) {
  115. // 1. Let script be the running script.
  116. // The running script is the script in the [[HostDefined]] field in the ScriptOrModule component of the running JavaScript execution context.
  117. HTML::Script* script { nullptr };
  118. s_main_thread_vm->running_execution_context().script_or_module.visit(
  119. [&script](JS::NonnullGCPtr<JS::Script>& js_script) {
  120. script = verify_cast<HTML::ClassicScript>(js_script->host_defined());
  121. },
  122. [&script](JS::NonnullGCPtr<JS::Module>& js_module) {
  123. script = verify_cast<HTML::ModuleScript>(js_module->host_defined());
  124. },
  125. [](Empty) {
  126. });
  127. // 2. If script is a classic script and script's muted errors is true, then return.
  128. // NOTE: is<T>() returns false if nullptr is passed.
  129. if (is<HTML::ClassicScript>(script)) {
  130. auto const& classic_script = static_cast<HTML::ClassicScript const&>(*script);
  131. if (classic_script.muted_errors() == HTML::ClassicScript::MutedErrors::Yes)
  132. return;
  133. }
  134. // 3. Let settings object be the current settings object.
  135. // 4. If script is not null, then set settings object to script's principal settings object.
  136. auto& settings_object = script ? script->settings_object() : HTML::current_principal_settings_object();
  137. // 5. Let global be settingsObject's global object.
  138. auto* global_mixin = dynamic_cast<HTML::WindowOrWorkerGlobalScopeMixin*>(&settings_object.global_object());
  139. VERIFY(global_mixin);
  140. auto& global = global_mixin->this_impl();
  141. switch (operation) {
  142. // 6. If operation is "reject",
  143. case JS::Promise::RejectionOperation::Reject:
  144. // 1. Append promise to global's about-to-be-notified rejected promises list.
  145. global_mixin->push_onto_about_to_be_notified_rejected_promises_list(promise);
  146. break;
  147. // 7. If operation is "handle",
  148. case JS::Promise::RejectionOperation::Handle: {
  149. // 1. If global's about-to-be-notified rejected promises list contains promise, then remove promise from that list and return.
  150. bool removed_about_to_be_notified_rejected_promise = global_mixin->remove_from_about_to_be_notified_rejected_promises_list(promise);
  151. if (removed_about_to_be_notified_rejected_promise)
  152. return;
  153. // 3. Remove promise from global's outstanding rejected promises weak set.
  154. bool removed_outstanding_rejected_promise = global_mixin->remove_from_outstanding_rejected_promises_weak_set(&promise);
  155. // 2. If global's outstanding rejected promises weak set does not contain promise, then return.
  156. // 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.
  157. if (!removed_outstanding_rejected_promise)
  158. return;
  159. // 4. Queue a global task on the DOM manipulation task source given global to fire an event named rejectionhandled at global, using PromiseRejectionEvent,
  160. // with the promise attribute initialized to promise, and the reason attribute initialized to the value of promise's [[PromiseResult]] internal slot.
  161. HTML::queue_global_task(HTML::Task::Source::DOMManipulation, global, JS::create_heap_function(s_main_thread_vm->heap(), [&global, &promise] {
  162. // FIXME: This currently assumes that global is a WindowObject.
  163. auto& window = verify_cast<HTML::Window>(global);
  164. HTML::PromiseRejectionEventInit event_init {
  165. {}, // Initialize the inherited DOM::EventInit
  166. /* .promise = */ promise,
  167. /* .reason = */ promise.result(),
  168. };
  169. auto promise_rejection_event = HTML::PromiseRejectionEvent::create(HTML::relevant_realm(global), HTML::EventNames::rejectionhandled, event_init);
  170. window.dispatch_event(promise_rejection_event);
  171. }));
  172. break;
  173. }
  174. default:
  175. VERIFY_NOT_REACHED();
  176. }
  177. };
  178. // 8.1.5.4.1 HostCallJobCallback(callback, V, argumentsList), https://html.spec.whatwg.org/multipage/webappapis.html#hostcalljobcallback
  179. // https://whatpr.org/html/9893/webappapis.html#hostcalljobcallback
  180. s_main_thread_vm->host_call_job_callback = [](JS::JobCallback& callback, JS::Value this_value, ReadonlySpan<JS::Value> arguments_list) {
  181. auto& callback_host_defined = verify_cast<WebEngineCustomJobCallbackData>(*callback.custom_data());
  182. // 1. Let incumbent realm be callback.[[HostDefined]].[[IncumbentRealm]]. (NOTE: Not necessary)
  183. // 2. Let script execution context be callback.[[HostDefined]].[[ActiveScriptContext]]. (NOTE: Not necessary)
  184. // 3. Prepare to run a callback with incumbent realm.
  185. HTML::prepare_to_run_callback(callback_host_defined.incumbent_settings->realm());
  186. // 4. If script execution context is not null, then push script execution context onto the JavaScript execution context stack.
  187. if (callback_host_defined.active_script_context)
  188. s_main_thread_vm->push_execution_context(*callback_host_defined.active_script_context);
  189. // 5. Let result be Call(callback.[[Callback]], V, argumentsList).
  190. auto result = JS::call(*s_main_thread_vm, callback.callback(), this_value, arguments_list);
  191. // 6. If script execution context is not null, then pop script execution context from the JavaScript execution context stack.
  192. if (callback_host_defined.active_script_context) {
  193. VERIFY(&s_main_thread_vm->running_execution_context() == callback_host_defined.active_script_context.ptr());
  194. s_main_thread_vm->pop_execution_context();
  195. }
  196. // 7. Clean up after running a callback with incumbent realm.
  197. HTML::clean_up_after_running_callback(callback_host_defined.incumbent_settings->realm());
  198. // 8. Return result.
  199. return result;
  200. };
  201. // 8.1.5.4.2 HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuefinalizationregistrycleanupjob
  202. s_main_thread_vm->host_enqueue_finalization_registry_cleanup_job = [](JS::FinalizationRegistry& finalization_registry) {
  203. // 1. Let global be finalizationRegistry.[[Realm]]'s global object.
  204. auto& global = finalization_registry.realm().global_object();
  205. // 2. Queue a global task on the JavaScript engine task source given global to perform the following steps:
  206. HTML::queue_global_task(HTML::Task::Source::JavaScriptEngine, global, JS::create_heap_function(s_main_thread_vm->heap(), [&finalization_registry] {
  207. // 1. Let entry be finalizationRegistry.[[CleanupCallback]].[[Callback]].[[Realm]].
  208. auto& entry = *finalization_registry.cleanup_callback().callback().realm();
  209. // 2. Check if we can run script with entry. If this returns "do not run", then return.
  210. if (HTML::can_run_script(entry) == HTML::RunScriptDecision::DoNotRun)
  211. return;
  212. // 3. Prepare to run script with entry.
  213. HTML::prepare_to_run_script(entry);
  214. // 4. Let result be the result of performing CleanupFinalizationRegistry(finalizationRegistry).
  215. auto result = finalization_registry.cleanup();
  216. // 5. Clean up after running script with entry.
  217. HTML::clean_up_after_running_script(entry);
  218. // 6. If result is an abrupt completion, then report the exception given by result.[[Value]].
  219. if (result.is_error())
  220. HTML::report_exception(result, entry);
  221. }));
  222. };
  223. // 8.1.5.4.3 HostEnqueuePromiseJob(job, realm), https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuepromisejob
  224. s_main_thread_vm->host_enqueue_promise_job = [](JS::NonnullGCPtr<JS::HeapFunction<JS::ThrowCompletionOr<JS::Value>()>> job, JS::Realm* realm) {
  225. // 1. If realm is not null, then let job settings be the settings object for realm. Otherwise, let job settings be null.
  226. HTML::EnvironmentSettingsObject* job_settings { nullptr };
  227. if (realm)
  228. job_settings = &host_defined_environment_settings_object(*realm);
  229. // 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
  230. // also be the active script or module of the job at the time of its invocation.
  231. // This means taking it here now and passing it through to the lambda.
  232. auto script_or_module = s_main_thread_vm->get_active_script_or_module();
  233. // 2. Queue a microtask on the surrounding agent's event loop to perform the following steps:
  234. // 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."
  235. // 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
  236. auto* script = active_script();
  237. auto& heap = realm ? realm->heap() : s_main_thread_vm->heap();
  238. // NOTE: This keeps job_settings alive by keeping realm alive, which is holding onto job_settings.
  239. HTML::queue_a_microtask(script ? script->settings_object().responsible_document().ptr() : nullptr, JS::create_heap_function(heap, [realm, job_settings, job = move(job), script_or_module = move(script_or_module)] {
  240. // The dummy execution context has to be kept up here to keep it alive for the duration of the function.
  241. OwnPtr<JS::ExecutionContext> dummy_execution_context;
  242. if (realm) {
  243. // 1. If realm is not null, then check if we can run script with realm. If this returns "do not run" then return.
  244. if (HTML::can_run_script(*realm) == HTML::RunScriptDecision::DoNotRun)
  245. return;
  246. // 2. If realm is not null, then prepare to run script with realm.
  247. HTML::prepare_to_run_script(*realm);
  248. // IMPLEMENTATION DEFINED: Additionally to preparing to run a script, we also prepare to run a callback here. This matches WebIDL's
  249. // invoke_callback() / call_user_object_operation() functions, and prevents a crash in host_make_job_callback()
  250. // when getting the incumbent settings object.
  251. HTML::prepare_to_run_callback(*realm);
  252. // IMPLEMENTATION DEFINED: Per the previous "implementation defined" comment, we must now make the script or module the active script or module.
  253. // Since the only active execution context currently is the realm execution context of job settings, lets attach it here.
  254. job_settings->realm_execution_context().script_or_module = script_or_module;
  255. } else {
  256. // FIXME: We need to setup a dummy execution context in case a JS::NativeFunction is called when processing the job.
  257. // 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.
  258. // 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
  259. dummy_execution_context = JS::ExecutionContext::create();
  260. dummy_execution_context->script_or_module = script_or_module;
  261. s_main_thread_vm->push_execution_context(*dummy_execution_context);
  262. }
  263. // 3. Let result be job().
  264. auto result = job->function()();
  265. // 4. If realm is not null, then clean up after running script with job settings.
  266. if (realm) {
  267. // IMPLEMENTATION DEFINED: Disassociate the realm execution context from the script or module.
  268. job_settings->realm_execution_context().script_or_module = Empty {};
  269. // IMPLEMENTATION DEFINED: See comment above, we need to clean up the non-standard prepare_to_run_callback() call.
  270. HTML::clean_up_after_running_callback(*realm);
  271. HTML::clean_up_after_running_script(*realm);
  272. } else {
  273. // Pop off the dummy execution context. See the above FIXME block about why this is done.
  274. s_main_thread_vm->pop_execution_context();
  275. }
  276. // 5. If result is an abrupt completion, then report the exception given by result.[[Value]].
  277. if (result.is_error())
  278. HTML::report_exception(result, job_settings->realm());
  279. }));
  280. };
  281. // 8.1.5.4.4 HostMakeJobCallback(callable), https://html.spec.whatwg.org/multipage/webappapis.html#hostmakejobcallback
  282. s_main_thread_vm->host_make_job_callback = [](JS::FunctionObject& callable) -> JS::NonnullGCPtr<JS::JobCallback> {
  283. // 1. Let incumbent settings be the incumbent settings object.
  284. auto& incumbent_settings = HTML::incumbent_settings_object();
  285. // 2. Let active script be the active script.
  286. auto* script = active_script();
  287. // 3. Let script execution context be null.
  288. OwnPtr<JS::ExecutionContext> script_execution_context;
  289. // 4. If active script is not null, set script execution context to a new JavaScript execution context, with its Function field set to null,
  290. // its Realm field set to active script's settings object's Realm, and its ScriptOrModule set to active script's record.
  291. if (script) {
  292. script_execution_context = JS::ExecutionContext::create();
  293. script_execution_context->function = nullptr;
  294. script_execution_context->realm = &script->settings_object().realm();
  295. if (is<HTML::ClassicScript>(script)) {
  296. script_execution_context->script_or_module = JS::NonnullGCPtr<JS::Script>(*verify_cast<HTML::ClassicScript>(script)->script_record());
  297. } else if (is<HTML::ModuleScript>(script)) {
  298. if (is<HTML::JavaScriptModuleScript>(script)) {
  299. script_execution_context->script_or_module = JS::NonnullGCPtr<JS::Module>(*verify_cast<HTML::JavaScriptModuleScript>(script)->record());
  300. } else {
  301. // NOTE: Handle CSS and JSON module scripts once we have those.
  302. VERIFY_NOT_REACHED();
  303. }
  304. } else {
  305. VERIFY_NOT_REACHED();
  306. }
  307. }
  308. // 5. Return the JobCallback Record { [[Callback]]: callable, [[HostDefined]]: { [[IncumbentSettings]]: incumbent settings, [[ActiveScriptContext]]: script execution context } }.
  309. auto host_defined = adopt_own(*new WebEngineCustomJobCallbackData(incumbent_settings, move(script_execution_context)));
  310. return JS::JobCallback::create(*s_main_thread_vm, callable, move(host_defined));
  311. };
  312. // 8.1.5.5.1 HostGetImportMetaProperties(moduleRecord), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetimportmetaproperties
  313. s_main_thread_vm->host_get_import_meta_properties = [](JS::SourceTextModule& module_record) {
  314. auto& realm = module_record.realm();
  315. auto& vm = realm.vm();
  316. // 1. Let moduleScript be moduleRecord.[[HostDefined]].
  317. auto& module_script = *verify_cast<HTML::Script>(module_record.host_defined());
  318. // 2. Assert: moduleScript's base URL is not null, as moduleScript is a JavaScript module script.
  319. VERIFY(module_script.base_url().is_valid());
  320. // 3. Let urlString be moduleScript's base URL, serialized.
  321. auto url_string = module_script.base_url().serialize();
  322. // 4. Let steps be the following steps, given the argument specifier:
  323. auto steps = [module_script = JS::NonnullGCPtr { module_script }](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  324. auto specifier = vm.argument(0);
  325. // 1. Set specifier to ? ToString(specifier).
  326. auto specifier_string = TRY(specifier.to_string(vm));
  327. // 2. Let url be the result of resolving a module specifier given moduleScript and specifier.
  328. auto url = TRY(Bindings::throw_dom_exception_if_needed(vm, [&] {
  329. return HTML::resolve_module_specifier(*module_script, specifier_string.to_byte_string());
  330. }));
  331. // 3. Return the serialization of url.
  332. return JS::PrimitiveString::create(vm, url.serialize());
  333. };
  334. // 4. Let resolveFunction be ! CreateBuiltinFunction(steps, 1, "resolve", « »).
  335. auto resolve_function = JS::NativeFunction::create(realm, move(steps), 1, vm.names.resolve);
  336. // 5. Return « Record { [[Key]]: "url", [[Value]]: urlString }, Record { [[Key]]: "resolve", [[Value]]: resolveFunction } ».
  337. HashMap<JS::PropertyKey, JS::Value> meta;
  338. meta.set("url", JS::PrimitiveString::create(vm, move(url_string)));
  339. meta.set("resolve", resolve_function);
  340. return meta;
  341. };
  342. // FIXME: Implement 8.1.5.5.2 HostImportModuleDynamically(referencingScriptOrModule, moduleRequest, promiseCapability), https://html.spec.whatwg.org/multipage/webappapis.html#hostimportmoduledynamically(referencingscriptormodule,-modulerequest,-promisecapability)
  343. // FIXME: Implement 8.1.5.5.3 HostResolveImportedModule(referencingScriptOrModule, moduleRequest), https://html.spec.whatwg.org/multipage/webappapis.html#hostresolveimportedmodule(referencingscriptormodule,-modulerequest)
  344. // 8.1.6.5.2 HostGetSupportedImportAttributes(), https://html.spec.whatwg.org/multipage/webappapis.html#hostgetsupportedimportassertions
  345. s_main_thread_vm->host_get_supported_import_attributes = []() -> Vector<ByteString> {
  346. // 1. Return « "type" ».
  347. return { "type"sv };
  348. };
  349. // 8.1.6.7.3 HostLoadImportedModule(referrer, moduleRequest, loadState, payload), https://html.spec.whatwg.org/multipage/webappapis.html#hostloadimportedmodule
  350. // https://whatpr.org/html/9893/webappapis.html#hostloadimportedmodule
  351. s_main_thread_vm->host_load_imported_module = [](JS::ImportedModuleReferrer referrer, JS::ModuleRequest const& module_request, JS::GCPtr<JS::GraphLoadingState::HostDefined> load_state, JS::ImportedModulePayload payload) -> void {
  352. auto& vm = *s_main_thread_vm;
  353. auto& realm = *vm.current_realm();
  354. // 1. Let settingsObject be the current principal settings object.
  355. Optional<HTML::EnvironmentSettingsObject&> settings_object = HTML::current_principal_settings_object();
  356. // FIXME: 2. If settingsObject's global object implements WorkletGlobalScope or ServiceWorkerGlobalScope and loadState is undefined, then:
  357. // 3. Let referencingScript be null.
  358. Optional<HTML::Script&> referencing_script;
  359. // 4. Let originalFetchOptions be the default script fetch options.
  360. auto original_fetch_options = HTML::default_script_fetch_options();
  361. // 5. Let fetchReferrer be "client".
  362. Fetch::Infrastructure::Request::ReferrerType fetch_referrer = Fetch::Infrastructure::Request::Referrer::Client;
  363. // 6. If referrer is a Script Record or a Cyclic Module Record, then:
  364. if (referrer.has<JS::NonnullGCPtr<JS::Script>>() || referrer.has<JS::NonnullGCPtr<JS::CyclicModule>>()) {
  365. // 1. Set referencingScript to referrer.[[HostDefined]].
  366. referencing_script = verify_cast<HTML::Script>(referrer.has<JS::NonnullGCPtr<JS::Script>>() ? *referrer.get<JS::NonnullGCPtr<JS::Script>>()->host_defined() : *referrer.get<JS::NonnullGCPtr<JS::CyclicModule>>()->host_defined());
  367. // 2. Set settingsObject to referencingScript's settings object.
  368. settings_object = referencing_script->settings_object();
  369. // 3. Set fetchReferrer to referencingScript's base URL.
  370. fetch_referrer = referencing_script->base_url();
  371. // FIXME: 4. Set originalFetchOptions to referencingScript's fetch options.
  372. }
  373. // FIXME: 7. If referrer is a Cyclic Module Record and moduleRequest is equal to the first element of referrer.[[RequestedModules]], then:
  374. // 8. Disallow further import maps given settingsObject.
  375. settings_object->disallow_further_import_maps();
  376. // 9. Let url be the result of resolving a module specifier given referencingScript and moduleRequest.[[Specifier]],
  377. // catching any exceptions. If they throw an exception, let resolutionError be the thrown exception.
  378. auto url = HTML::resolve_module_specifier(referencing_script, module_request.module_specifier);
  379. // 10. If the previous step threw an exception, then:
  380. if (url.is_exception()) {
  381. // 1. Let completion be Completion Record { [[Type]]: throw, [[Value]]: resolutionError, [[Target]]: empty }.
  382. auto completion = dom_exception_to_throw_completion(main_thread_vm(), url.exception());
  383. // 2. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, completion).
  384. HTML::TemporaryExecutionContext context { realm };
  385. JS::finish_loading_imported_module(referrer, module_request, payload, completion);
  386. // 3. Return.
  387. return;
  388. }
  389. // 11. Let fetchOptions be the result of getting the descendant script fetch options given originalFetchOptions, url, and settingsObject.
  390. auto fetch_options = MUST(HTML::get_descendant_script_fetch_options(original_fetch_options, url.value(), *settings_object));
  391. // 12. Let destination be "script".
  392. auto destination = Fetch::Infrastructure::Request::Destination::Script;
  393. // 13. Let fetchClient be settingsObject.
  394. JS::NonnullGCPtr fetch_client { *settings_object };
  395. // 14. If loadState is not undefined, then:
  396. HTML::PerformTheFetchHook perform_fetch;
  397. if (load_state) {
  398. auto& fetch_context = static_cast<HTML::FetchContext&>(*load_state);
  399. // 1. Set destination to loadState.[[Destination]].
  400. destination = fetch_context.destination;
  401. // 2. Set fetchClient to loadState.[[FetchClient]].
  402. fetch_client = fetch_context.fetch_client;
  403. // For step 13
  404. perform_fetch = fetch_context.perform_fetch;
  405. }
  406. auto on_single_fetch_complete = HTML::create_on_fetch_script_complete(realm.heap(), [referrer, &realm, load_state, module_request, payload](JS::GCPtr<HTML::Script> const& module_script) -> void {
  407. // onSingleFetchComplete given moduleScript is the following algorithm:
  408. // 1. Let completion be null.
  409. // NOTE: Our JS::Completion does not support non JS::Value types for its [[Value]], a such we
  410. // use JS::ThrowCompletionOr here.
  411. auto& vm = realm.vm();
  412. JS::GCPtr<JS::Module> module = nullptr;
  413. auto completion = [&]() -> JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Module>> {
  414. // 2. If moduleScript is null, then set completion to Completion Record { [[Type]]: throw, [[Value]]: a new TypeError, [[Target]]: empty }.
  415. if (!module_script) {
  416. return JS::throw_completion(JS::TypeError::create(realm, ByteString::formatted("Loading imported module '{}' failed.", module_request.module_specifier)));
  417. }
  418. // 3. Otherwise, if moduleScript's parse error is not null, then:
  419. else if (!module_script->parse_error().is_null()) {
  420. // 1. Let parseError be moduleScript's parse error.
  421. auto parse_error = module_script->parse_error();
  422. // 2. Set completion to Completion Record { [[Type]]: throw, [[Value]]: parseError, [[Target]]: empty }.
  423. auto completion = JS::throw_completion(parse_error);
  424. // 3. If loadState is not undefined and loadState.[[ParseError]] is null, set loadState.[[ParseError]] to parseError.
  425. if (load_state) {
  426. auto& load_state_as_fetch_context = static_cast<HTML::FetchContext&>(*load_state);
  427. if (load_state_as_fetch_context.parse_error.is_null()) {
  428. load_state_as_fetch_context.parse_error = parse_error;
  429. }
  430. }
  431. return completion;
  432. }
  433. // 4. Otherwise, set completion to Completion Record { [[Type]]: normal, [[Value]]: moduleScript's record, [[Target]]: empty }.
  434. else {
  435. module = static_cast<HTML::JavaScriptModuleScript&>(*module_script).record();
  436. return JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Module>>(*module);
  437. }
  438. }();
  439. // 5. Perform FinishLoadingImportedModule(referrer, moduleRequest, payload, completion).
  440. // NON-STANDARD: To ensure that LibJS can find the module on the stack, we push a new execution context.
  441. auto module_execution_context = JS::ExecutionContext::create();
  442. module_execution_context->realm = realm;
  443. if (module)
  444. module_execution_context->script_or_module = JS::NonnullGCPtr { *module };
  445. vm.push_execution_context(*module_execution_context);
  446. JS::finish_loading_imported_module(referrer, module_request, payload, completion);
  447. vm.pop_execution_context();
  448. });
  449. // 15. Fetch a single imported module script given url, fetchClient, destination, fetchOptions, settingsObject, fetchReferrer,
  450. // moduleRequest, and onSingleFetchComplete as defined below.
  451. // If loadState is not undefined and loadState.[[PerformFetch]] is not null, pass loadState.[[PerformFetch]] along as well.
  452. HTML::fetch_single_imported_module_script(realm, url.release_value(), *fetch_client, destination, fetch_options, *settings_object, fetch_referrer, module_request, perform_fetch, on_single_fetch_complete);
  453. };
  454. s_main_thread_vm->host_unrecognized_date_string = [](StringView date) {
  455. dbgln("Unable to parse date string: \"{}\"", date);
  456. };
  457. return {};
  458. }
  459. JS::VM& main_thread_vm()
  460. {
  461. VERIFY(s_main_thread_vm);
  462. return *s_main_thread_vm;
  463. }
  464. // https://dom.spec.whatwg.org/#queue-a-mutation-observer-compound-microtask
  465. void queue_mutation_observer_microtask(DOM::Document const& document)
  466. {
  467. auto& vm = main_thread_vm();
  468. auto& custom_data = verify_cast<WebEngineCustomData>(*vm.custom_data());
  469. // 1. If the surrounding agent’s mutation observer microtask queued is true, then return.
  470. if (custom_data.mutation_observer_microtask_queued)
  471. return;
  472. // 2. Set the surrounding agent’s mutation observer microtask queued to true.
  473. custom_data.mutation_observer_microtask_queued = true;
  474. // 3. Queue a microtask to notify mutation observers.
  475. // 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.
  476. // FIXME: Is it safe to pass custom_data through?
  477. HTML::queue_a_microtask(&document, JS::create_heap_function(vm.heap(), [&custom_data, &heap = document.heap()]() {
  478. // 1. Set the surrounding agent’s mutation observer microtask queued to false.
  479. custom_data.mutation_observer_microtask_queued = false;
  480. // 2. Let notifySet be a clone of the surrounding agent’s mutation observers.
  481. JS::MarkedVector<DOM::MutationObserver*> notify_set(heap);
  482. for (auto& observer : custom_data.mutation_observers)
  483. notify_set.append(observer);
  484. // FIXME: 3. Let signalSet be a clone of the surrounding agent’s signal slots.
  485. // FIXME: 4. Empty the surrounding agent’s signal slots.
  486. // 5. For each mo of notifySet:
  487. for (auto& mutation_observer : notify_set) {
  488. // 1. Let records be a clone of mo’s record queue.
  489. // 2. Empty mo’s record queue.
  490. auto records = mutation_observer->take_records();
  491. // 3. For each node of mo’s node list, remove all transient registered observers whose observer is mo from node’s registered observer list.
  492. for (auto& node : mutation_observer->node_list()) {
  493. // FIXME: Is this correct?
  494. if (node.is_null())
  495. continue;
  496. if (node->registered_observer_list()) {
  497. node->registered_observer_list()->remove_all_matching([&mutation_observer](DOM::RegisteredObserver& registered_observer) {
  498. return is<DOM::TransientRegisteredObserver>(registered_observer) && static_cast<DOM::TransientRegisteredObserver&>(registered_observer).observer().ptr() == mutation_observer;
  499. });
  500. }
  501. }
  502. // 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.
  503. if (!records.is_empty()) {
  504. auto& callback = mutation_observer->callback();
  505. auto& realm = callback.callback_context->realm();
  506. auto wrapped_records = MUST(JS::Array::create(realm, 0));
  507. for (size_t i = 0; i < records.size(); ++i) {
  508. auto& record = records.at(i);
  509. auto property_index = JS::PropertyKey { i };
  510. MUST(wrapped_records->create_data_property(property_index, record.ptr()));
  511. }
  512. auto result = WebIDL::invoke_callback(callback, mutation_observer, wrapped_records, mutation_observer);
  513. if (result.is_abrupt())
  514. HTML::report_exception(result, realm);
  515. }
  516. }
  517. // FIXME: 6. For each slot of signalSet, fire an event named slotchange, with its bubbles attribute set to true, at slot.
  518. }));
  519. }
  520. // https://html.spec.whatwg.org/multipage/webappapis.html#creating-a-new-javascript-realm
  521. 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)
  522. {
  523. // 1. Perform InitializeHostDefinedRealm() with the provided customizations for creating the global object and the global this binding.
  524. // 2. Let realm execution context be the running JavaScript execution context.
  525. auto realm_execution_context = MUST(JS::Realm::initialize_host_defined_realm(vm, move(create_global_object), move(create_global_this_value)));
  526. // 3. Remove realm execution context from the JavaScript execution context stack.
  527. vm.execution_context_stack().remove_first_matching([&realm_execution_context](auto execution_context) {
  528. return execution_context == realm_execution_context.ptr();
  529. });
  530. // NO-OP: 4. Let realm be realm execution context's Realm component.
  531. // NO-OP: 5. Set realm's agent to agent.
  532. // FIXME: 6. If agent's agent cluster's cross-origin isolation mode is "none", then:
  533. // 1. Let global be realm's global object.
  534. // 2. Let status be ! global.[[Delete]]("SharedArrayBuffer").
  535. // 3. Assert: status is true.
  536. // 7. Return realm execution context.
  537. return realm_execution_context;
  538. }
  539. void WebEngineCustomData::spin_event_loop_until(JS::Handle<JS::HeapFunction<bool()>> goal_condition)
  540. {
  541. Platform::EventLoopPlugin::the().spin_until(move(goal_condition));
  542. }
  543. // https://html.spec.whatwg.org/multipage/custom-elements.html#invoke-custom-element-reactions
  544. void invoke_custom_element_reactions(Vector<JS::Handle<DOM::Element>>& element_queue)
  545. {
  546. // 1. While queue is not empty:
  547. while (!element_queue.is_empty()) {
  548. // 1. Let element be the result of dequeuing from queue.
  549. auto element = element_queue.take_first();
  550. // 2. Let reactions be element's custom element reaction queue.
  551. auto* reactions = element->custom_element_reaction_queue();
  552. // 3. Repeat until reactions is empty:
  553. if (!reactions)
  554. continue;
  555. while (!reactions->is_empty()) {
  556. // 1. Remove the first element of reactions, and let reaction be that element. Switch on reaction's type:
  557. auto reaction = reactions->take_first();
  558. auto maybe_exception = reaction.visit(
  559. [&](DOM::CustomElementUpgradeReaction const& custom_element_upgrade_reaction) -> JS::ThrowCompletionOr<void> {
  560. // -> upgrade reaction
  561. // Upgrade element using reaction's custom element definition.
  562. return element->upgrade_element(*custom_element_upgrade_reaction.custom_element_definition);
  563. },
  564. [&](DOM::CustomElementCallbackReaction& custom_element_callback_reaction) -> JS::ThrowCompletionOr<void> {
  565. // -> callback reaction
  566. // Invoke reaction's callback function with reaction's arguments, and with element as the callback this value.
  567. auto result = WebIDL::invoke_callback(*custom_element_callback_reaction.callback, element.ptr(), custom_element_callback_reaction.arguments);
  568. if (result.is_abrupt())
  569. return result.release_error();
  570. return {};
  571. });
  572. // If this throws an exception, catch it, and report the exception.
  573. if (maybe_exception.is_throw_completion())
  574. HTML::report_exception(maybe_exception, element->realm());
  575. }
  576. }
  577. }
  578. }