Fetching.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. /*
  2. * Copyright (c) 2022-2023, networkException <networkexception@serenityos.org>
  3. * Copyright (c) 2024, Tim Ledbetter <timledbetter@gmail.com>
  4. * Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibCore/EventLoop.h>
  9. #include <LibGC/Function.h>
  10. #include <LibJS/Runtime/ModuleRequest.h>
  11. #include <LibTextCodec/Decoder.h>
  12. #include <LibWeb/Bindings/MainThreadVM.h>
  13. #include <LibWeb/Bindings/PrincipalHostDefined.h>
  14. #include <LibWeb/DOM/Document.h>
  15. #include <LibWeb/DOMURL/DOMURL.h>
  16. #include <LibWeb/Fetch/Fetching/Fetching.h>
  17. #include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
  18. #include <LibWeb/Fetch/Infrastructure/HTTP/Headers.h>
  19. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  20. #include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
  21. #include <LibWeb/Fetch/Infrastructure/URL.h>
  22. #include <LibWeb/HTML/HTMLScriptElement.h>
  23. #include <LibWeb/HTML/PotentialCORSRequest.h>
  24. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  25. #include <LibWeb/HTML/Scripting/Environments.h>
  26. #include <LibWeb/HTML/Scripting/Fetching.h>
  27. #include <LibWeb/HTML/Scripting/ModuleScript.h>
  28. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  29. #include <LibWeb/HTML/Window.h>
  30. #include <LibWeb/Infra/Strings.h>
  31. #include <LibWeb/MimeSniff/MimeType.h>
  32. namespace Web::HTML {
  33. GC_DEFINE_ALLOCATOR(FetchContext);
  34. OnFetchScriptComplete create_on_fetch_script_complete(GC::Heap& heap, Function<void(GC::Ptr<Script>)> function)
  35. {
  36. return GC::create_function(heap, move(function));
  37. }
  38. PerformTheFetchHook create_perform_the_fetch_hook(GC::Heap& heap, Function<WebIDL::ExceptionOr<void>(GC::Ref<Fetch::Infrastructure::Request>, TopLevelModule, Fetch::Infrastructure::FetchAlgorithms::ProcessResponseConsumeBodyFunction)> function)
  39. {
  40. return GC::create_function(heap, move(function));
  41. }
  42. ScriptFetchOptions default_script_fetch_options()
  43. {
  44. // The default script fetch options are a script fetch options whose cryptographic nonce is the empty string,
  45. // integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is "same-origin",
  46. // referrer policy is the empty string, and fetch priority is "auto".
  47. return ScriptFetchOptions {
  48. .cryptographic_nonce = {},
  49. .integrity_metadata = {},
  50. .parser_metadata = Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted,
  51. .credentials_mode = Fetch::Infrastructure::Request::CredentialsMode::SameOrigin,
  52. .referrer_policy = {},
  53. .fetch_priority = Fetch::Infrastructure::Request::Priority::Auto
  54. };
  55. }
  56. // https://html.spec.whatwg.org/multipage/webappapis.html#module-type-from-module-request
  57. ByteString module_type_from_module_request(JS::ModuleRequest const& module_request)
  58. {
  59. // 1. Let moduleType be "javascript".
  60. ByteString module_type = "javascript"sv;
  61. // 2. If moduleRequest.[[Attributes]] has a Record entry such that entry.[[Key]] is "type", then:
  62. for (auto const& entry : module_request.attributes) {
  63. if (entry.key != "type"sv)
  64. continue;
  65. // 1. If entry.[[Value]] is "javascript", then set moduleType to null.
  66. if (entry.value == "javascript"sv)
  67. module_type = nullptr;
  68. // 2. Otherwise, set moduleType to entry.[[Value]].
  69. else
  70. module_type = entry.value;
  71. }
  72. // 3. Return moduleType.
  73. return module_type;
  74. }
  75. // https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier
  76. // https://whatpr.org/html/9893/webappapis.html#resolve-a-module-specifier
  77. WebIDL::ExceptionOr<URL::URL> resolve_module_specifier(Optional<Script&> referring_script, ByteString const& specifier)
  78. {
  79. auto& vm = Bindings::main_thread_vm();
  80. // 1. Let realm and baseURL be null.
  81. GC::Ptr<JS::Realm> realm;
  82. Optional<URL::URL> base_url;
  83. // 2. If referringScript is not null, then:
  84. if (referring_script.has_value()) {
  85. // 1. Set realm to referringScript's realm.
  86. realm = referring_script->realm();
  87. // 2. Set baseURL to referringScript's base URL.
  88. base_url = referring_script->base_url();
  89. }
  90. // 3. Otherwise:
  91. else {
  92. // 1. Assert: there is a current realm.
  93. VERIFY(vm.current_realm());
  94. // 2. Set realm to the current realm.
  95. realm = *vm.current_realm();
  96. // 3. Set baseURL to realm's principal realm's settings object's API base URL.
  97. base_url = Bindings::principal_host_defined_environment_settings_object(HTML::principal_realm(*realm)).api_base_url();
  98. }
  99. // 4. Let importMap be an empty import map.
  100. ImportMap import_map;
  101. // 5. If realm's global object implements Window, then set importMap to settingsObject's global object's import map.
  102. if (is<Window>(realm->global_object()))
  103. import_map = verify_cast<Window>(realm->global_object()).import_map();
  104. // 6. Let serializedBaseURL be baseURL, serialized.
  105. auto serialized_base_url = base_url->serialize();
  106. // 7. Let asURL be the result of resolving a URL-like module specifier given specifier and baseURL.
  107. auto as_url = resolve_url_like_module_specifier(specifier, *base_url);
  108. // 8. Let normalizedSpecifier be the serialization of asURL, if asURL is non-null; otherwise, specifier.
  109. auto normalized_specifier = as_url.has_value() ? as_url->serialize().to_byte_string() : specifier;
  110. // 9. Let result be a URL-or-null, initially null.
  111. Optional<URL::URL> result;
  112. // 10. For each scopePrefix → scopeImports of importMap's scopes:
  113. for (auto const& entry : import_map.scopes()) {
  114. // FIXME: Clarify if the serialization steps need to be run here. The steps below assume
  115. // scopePrefix to be a string.
  116. auto const& scope_prefix = entry.key.serialize();
  117. auto const& scope_imports = entry.value;
  118. // 1. If scopePrefix is serializedBaseURL, or if scopePrefix ends with U+002F (/) and scopePrefix is a code unit prefix of serializedBaseURL, then:
  119. if (scope_prefix == serialized_base_url || (scope_prefix.ends_with('/') && Infra::is_code_unit_prefix(scope_prefix, serialized_base_url))) {
  120. // 1. Let scopeImportsMatch be the result of resolving an imports match given normalizedSpecifier, asURL, and scopeImports.
  121. auto scope_imports_match = TRY(resolve_imports_match(normalized_specifier, as_url, scope_imports));
  122. // 2. If scopeImportsMatch is not null, then set result to scopeImportsMatch, and break.
  123. if (scope_imports_match.has_value()) {
  124. result = scope_imports_match.release_value();
  125. break;
  126. }
  127. }
  128. }
  129. // 11. If result is null, set result be the result of resolving an imports match given normalizedSpecifier, asURL, and importMap's imports.
  130. if (!result.has_value())
  131. result = TRY(resolve_imports_match(normalized_specifier, as_url, import_map.imports()));
  132. // 12. If result is null, set it to asURL.
  133. // Spec-Note: By this point, if result was null, specifier wasn't remapped to anything by importMap, but it might have been able to be turned into a URL.
  134. if (!result.has_value())
  135. result = as_url;
  136. // 13. If result is not null, then:
  137. if (result.has_value()) {
  138. // 1. Add module to resolved module set given realm, serializedBaseURL, normalizedSpecifier, and asURL.
  139. add_module_to_resolved_module_set(*realm, serialized_base_url, MUST(String::from_byte_string(normalized_specifier)), as_url);
  140. // 2. Return result.
  141. return result.release_value();
  142. }
  143. // 14. Throw a TypeError indicating that specifier was a bare specifier, but was not remapped to anything by importMap.
  144. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, MUST(String::formatted("Failed to resolve non relative module specifier '{}' from an import map.", specifier)) };
  145. }
  146. // https://html.spec.whatwg.org/multipage/webappapis.html#resolving-an-imports-match
  147. WebIDL::ExceptionOr<Optional<URL::URL>> resolve_imports_match(ByteString const& normalized_specifier, Optional<URL::URL> as_url, ModuleSpecifierMap const& specifier_map)
  148. {
  149. // 1. For each specifierKey → resolutionResult of specifierMap:
  150. for (auto const& [specifier_key, resolution_result] : specifier_map) {
  151. // 1. If specifierKey is normalizedSpecifier, then:
  152. if (specifier_key == normalized_specifier) {
  153. // 1. If resolutionResult is null, then throw a TypeError indicating that resolution of specifierKey was blocked by a null entry.
  154. if (!resolution_result.has_value())
  155. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Import resolution of '{}' was blocked by a null entry.", specifier_key).release_value_but_fixme_should_propagate_errors() };
  156. // 2. Assert: resolutionResult is a URL.
  157. VERIFY(resolution_result->is_valid());
  158. // 3. Return resolutionResult.
  159. return resolution_result;
  160. }
  161. // 2. If all of the following are true:
  162. if (
  163. // - specifierKey ends with U+002F (/);
  164. specifier_key.ends_with("/"sv) &&
  165. // - specifierKey is a code unit prefix of normalizedSpecifier; and
  166. Infra::is_code_unit_prefix(specifier_key, normalized_specifier) &&
  167. // - either asURL is null, or asURL is special,
  168. (!as_url.has_value() || as_url->is_special())
  169. // then:
  170. ) {
  171. // 1. If resolutionResult is null, then throw a TypeError indicating that the resolution of specifierKey was blocked by a null entry.
  172. if (!resolution_result.has_value())
  173. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Import resolution of '{}' was blocked by a null entry.", specifier_key).release_value_but_fixme_should_propagate_errors() };
  174. // 2. Assert: resolutionResult is a URL.
  175. VERIFY(resolution_result->is_valid());
  176. // 3. Let afterPrefix be the portion of normalizedSpecifier after the initial specifierKey prefix.
  177. // FIXME: Clarify if this is meant by the portion after the initial specifierKey prefix.
  178. auto after_prefix = normalized_specifier.substring(specifier_key.length());
  179. // 4. Assert: resolutionResult, serialized, ends with U+002F (/), as enforced during parsing.
  180. VERIFY(resolution_result->serialize().ends_with('/'));
  181. // 5. Let url be the result of URL parsing afterPrefix with resolutionResult.
  182. auto url = DOMURL::parse(after_prefix, *resolution_result);
  183. // 6. If url is failure, then throw a TypeError indicating that resolution of normalizedSpecifier was blocked since the afterPrefix portion
  184. // could not be URL-parsed relative to the resolutionResult mapped to by the specifierKey prefix.
  185. if (!url.is_valid())
  186. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Could not resolve '{}' as the after prefix portion could not be URL-parsed.", normalized_specifier).release_value_but_fixme_should_propagate_errors() };
  187. // 7. Assert: url is a URL.
  188. VERIFY(url.is_valid());
  189. // 8. If the serialization of resolutionResult is not a code unit prefix of the serialization of url, then throw a TypeError indicating
  190. // that the resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.
  191. if (!Infra::is_code_unit_prefix(resolution_result->serialize(), url.serialize()))
  192. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Could not resolve '{}' as it backtracks above its prefix specifierKey.", normalized_specifier).release_value_but_fixme_should_propagate_errors() };
  193. // 9. Return url.
  194. return url;
  195. }
  196. }
  197. // 2. Return null.
  198. return Optional<URL::URL> {};
  199. }
  200. // https://html.spec.whatwg.org/multipage/webappapis.html#resolving-a-url-like-module-specifier
  201. Optional<URL::URL> resolve_url_like_module_specifier(ByteString const& specifier, URL::URL const& base_url)
  202. {
  203. // 1. If specifier starts with "/", "./", or "../", then:
  204. if (specifier.starts_with("/"sv) || specifier.starts_with("./"sv) || specifier.starts_with("../"sv)) {
  205. // 1. Let url be the result of URL parsing specifier with baseURL.
  206. auto url = DOMURL::parse(specifier, base_url);
  207. // 2. If url is failure, then return null.
  208. if (!url.is_valid())
  209. return {};
  210. // 3. Return url.
  211. return url;
  212. }
  213. // 2. Let url be the result of URL parsing specifier (with no base URL).
  214. auto url = DOMURL::parse(specifier);
  215. // 3. If url is failure, then return null.
  216. if (!url.is_valid())
  217. return {};
  218. // 4. Return url.
  219. return url;
  220. }
  221. // https://html.spec.whatwg.org/multipage/webappapis.html#set-up-the-classic-script-request
  222. static void set_up_classic_script_request(Fetch::Infrastructure::Request& request, ScriptFetchOptions const& options)
  223. {
  224. // Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's
  225. // integrity metadata, its parser metadata to options's parser metadata, its referrer policy to options's referrer
  226. // policy, its render-blocking to options's render-blocking, and its priority to options's fetch priority.
  227. request.set_cryptographic_nonce_metadata(options.cryptographic_nonce);
  228. request.set_integrity_metadata(options.integrity_metadata);
  229. request.set_parser_metadata(options.parser_metadata);
  230. request.set_referrer_policy(options.referrer_policy);
  231. request.set_render_blocking(options.render_blocking);
  232. request.set_priority(options.fetch_priority);
  233. }
  234. // https://html.spec.whatwg.org/multipage/webappapis.html#set-up-the-module-script-request
  235. static void set_up_module_script_request(Fetch::Infrastructure::Request& request, ScriptFetchOptions const& options)
  236. {
  237. // Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's
  238. // integrity metadata, its parser metadata to options's parser metadata, its credentials mode to options's credentials
  239. // mode, its referrer policy to options's referrer policy, its render-blocking to options's render-blocking, and its
  240. // priority to options's fetch priority.
  241. request.set_cryptographic_nonce_metadata(options.cryptographic_nonce);
  242. request.set_integrity_metadata(options.integrity_metadata);
  243. request.set_parser_metadata(options.parser_metadata);
  244. request.set_credentials_mode(options.credentials_mode);
  245. request.set_referrer_policy(options.referrer_policy);
  246. request.set_render_blocking(options.render_blocking);
  247. request.set_priority(options.fetch_priority);
  248. }
  249. // https://html.spec.whatwg.org/multipage/webappapis.html#get-the-descendant-script-fetch-options
  250. ScriptFetchOptions get_descendant_script_fetch_options(ScriptFetchOptions const& original_options, URL::URL const& url, EnvironmentSettingsObject& settings_object)
  251. {
  252. // 1. Let newOptions be a copy of originalOptions.
  253. auto new_options = original_options;
  254. // 2. Let integrity be the result of resolving a module integrity metadata with url and settingsObject.
  255. String integrity = resolve_a_module_integrity_metadata(url, settings_object);
  256. // 3. Set newOptions's integrity metadata to integrity.
  257. new_options.integrity_metadata = integrity;
  258. // 4. Set newOptions's fetch priority to "auto".
  259. new_options.fetch_priority = Fetch::Infrastructure::Request::Priority::Auto;
  260. // 5. Return newOptions.
  261. return new_options;
  262. }
  263. // https://html.spec.whatwg.org/multipage/webappapis.html#resolving-a-module-integrity-metadata
  264. String resolve_a_module_integrity_metadata(const URL::URL& url, EnvironmentSettingsObject& settings_object)
  265. {
  266. // 1. Let map be settingsObject's global object's import map.
  267. auto map = verify_cast<Window>(settings_object.global_object()).import_map();
  268. // 2. If map's integrity[url] does not exist, then return the empty string.
  269. // 3. Return map's integrity[url].
  270. return MUST(String::from_byte_string(map.integrity().get(url).value_or("")));
  271. }
  272. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-script
  273. WebIDL::ExceptionOr<void> fetch_classic_script(GC::Ref<HTMLScriptElement> element, URL::URL const& url, EnvironmentSettingsObject& settings_object, ScriptFetchOptions options, CORSSettingAttribute cors_setting, String character_encoding, OnFetchScriptComplete on_complete)
  274. {
  275. auto& realm = element->realm();
  276. auto& vm = realm.vm();
  277. // 1. Let request be the result of creating a potential-CORS request given url, "script", and CORS setting.
  278. auto request = create_potential_CORS_request(vm, url, Fetch::Infrastructure::Request::Destination::Script, cors_setting);
  279. // 2. Set request's client to settings object.
  280. request->set_client(&settings_object);
  281. // 3. Set request's initiator type to "script".
  282. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Script);
  283. // 4. Set up the classic script request given request and options.
  284. set_up_classic_script_request(*request, options);
  285. // 5. Fetch request with the following processResponseConsumeBody steps given response response and null, failure,
  286. // or a byte sequence bodyBytes:
  287. Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  288. fetch_algorithms_input.process_response_consume_body = [&settings_object, options = move(options), character_encoding = move(character_encoding), on_complete = move(on_complete)](auto response, auto body_bytes) {
  289. // 1. Set response to response's unsafe response.
  290. response = response->unsafe_response();
  291. // 2. If either of the following conditions are met:
  292. // - bodyBytes is null or failure; or
  293. // - response's status is not an ok status,
  294. if (body_bytes.template has<Empty>() || body_bytes.template has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>() || !Fetch::Infrastructure::is_ok_status(response->status())) {
  295. // then run onComplete given null, and abort these steps.
  296. on_complete->function()(nullptr);
  297. return;
  298. }
  299. // 3. Let potentialMIMETypeForEncoding be the result of extracting a MIME type given response's header list.
  300. auto potential_mime_type_for_encoding = response->header_list()->extract_mime_type();
  301. // 4. Set character encoding to the result of legacy extracting an encoding given potentialMIMETypeForEncoding
  302. // and character encoding.
  303. auto extracted_character_encoding = Fetch::Infrastructure::legacy_extract_an_encoding(potential_mime_type_for_encoding, character_encoding);
  304. // 5. Let source text be the result of decoding bodyBytes to Unicode, using character encoding as the fallback
  305. // encoding.
  306. auto fallback_decoder = TextCodec::decoder_for(extracted_character_encoding);
  307. VERIFY(fallback_decoder.has_value());
  308. auto source_text = TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*fallback_decoder, body_bytes.template get<ByteBuffer>()).release_value_but_fixme_should_propagate_errors();
  309. // 6. Let muted errors be true if response was CORS-cross-origin, and false otherwise.
  310. auto muted_errors = response->is_cors_cross_origin() ? ClassicScript::MutedErrors::Yes : ClassicScript::MutedErrors::No;
  311. // 7. Let script be the result of creating a classic script given source text, settings object's realm, response's URL,
  312. // options, and muted errors.
  313. // FIXME: Pass options.
  314. auto response_url = response->url().value_or({});
  315. auto script = ClassicScript::create(response_url.to_byte_string(), source_text, settings_object.realm(), response_url, 1, muted_errors);
  316. // 8. Run onComplete given script.
  317. on_complete->function()(script);
  318. };
  319. TRY(Fetch::Fetching::fetch(element->realm(), request, Fetch::Infrastructure::FetchAlgorithms::create(vm, move(fetch_algorithms_input))));
  320. return {};
  321. }
  322. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-worker-script
  323. WebIDL::ExceptionOr<void> fetch_classic_worker_script(URL::URL const& url, EnvironmentSettingsObject& fetch_client, Fetch::Infrastructure::Request::Destination destination, EnvironmentSettingsObject& settings_object, PerformTheFetchHook perform_fetch, OnFetchScriptComplete on_complete)
  324. {
  325. auto& realm = settings_object.realm();
  326. auto& vm = realm.vm();
  327. // 1. Let request be a new request whose URL is url, client is fetchClient, destination is destination, initiator type is "other",
  328. // mode is "same-origin", credentials mode is "same-origin", parser metadata is "not parser-inserted",
  329. // and whose use-URL-credentials flag is set.
  330. auto request = Fetch::Infrastructure::Request::create(vm);
  331. request->set_url(url);
  332. request->set_client(&fetch_client);
  333. request->set_destination(destination);
  334. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Other);
  335. // FIXME: Use proper SameOrigin CORS mode once Origins are set properly in WorkerHost processes
  336. request->set_mode(Fetch::Infrastructure::Request::Mode::NoCORS);
  337. request->set_credentials_mode(Fetch::Infrastructure::Request::CredentialsMode::SameOrigin);
  338. request->set_parser_metadata(Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted);
  339. request->set_use_url_credentials(true);
  340. auto process_response_consume_body = [&settings_object, on_complete = move(on_complete)](auto response, auto body_bytes) {
  341. // 1. Set response to response's unsafe response.
  342. response = response->unsafe_response();
  343. // 2. If either of the following conditions are met:
  344. // - bodyBytes is null or failure; or
  345. // - response's status is not an ok status,
  346. if (body_bytes.template has<Empty>() || body_bytes.template has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>() || !Fetch::Infrastructure::is_ok_status(response->status())) {
  347. // then run onComplete given null, and abort these steps.
  348. on_complete->function()(nullptr);
  349. return;
  350. }
  351. // 3. If all of the following are true:
  352. // - response's URL's scheme is an HTTP(S) scheme; and
  353. // - the result of extracting a MIME type from response's header list is not a JavaScript MIME type,
  354. auto maybe_mime_type = response->header_list()->extract_mime_type();
  355. auto mime_type_is_javascript = maybe_mime_type.has_value() && maybe_mime_type->is_javascript();
  356. if (response->url().has_value() && Fetch::Infrastructure::is_http_or_https_scheme(response->url()->scheme()) && !mime_type_is_javascript) {
  357. auto mime_type_serialized = maybe_mime_type.has_value() ? maybe_mime_type->serialized() : "unknown"_string;
  358. dbgln("Invalid non-javascript mime type \"{}\" for worker script at {}", mime_type_serialized, response->url().value());
  359. // then run onComplete given null, and abort these steps.
  360. on_complete->function()(nullptr);
  361. return;
  362. }
  363. // NOTE: Other fetch schemes are exempted from MIME type checking for historical web-compatibility reasons.
  364. // We might be able to tighten this in the future; see https://github.com/whatwg/html/issues/3255.
  365. // 4. Let sourceText be the result of UTF-8 decoding bodyBytes.
  366. auto decoder = TextCodec::decoder_for("UTF-8"sv);
  367. VERIFY(decoder.has_value());
  368. auto source_text = TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, body_bytes.template get<ByteBuffer>()).release_value_but_fixme_should_propagate_errors();
  369. // 5. Let script be the result of creating a classic script using sourceText, settingsObject's realm,
  370. // response's URL, and the default classic script fetch options.
  371. auto response_url = response->url().value_or({});
  372. auto script = ClassicScript::create(response_url.to_byte_string(), source_text, settings_object.realm(), response_url);
  373. // 6. Run onComplete given script.
  374. on_complete->function()(script);
  375. };
  376. // 2. If performFetch was given, run performFetch with request, true, and with processResponseConsumeBody as defined below.
  377. if (perform_fetch != nullptr) {
  378. TRY(perform_fetch->function()(request, TopLevelModule::Yes, move(process_response_consume_body)));
  379. }
  380. // Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.
  381. else {
  382. Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  383. fetch_algorithms_input.process_response_consume_body = move(process_response_consume_body);
  384. TRY(Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(vm, move(fetch_algorithms_input))));
  385. }
  386. return {};
  387. }
  388. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-worker-imported-script
  389. WebIDL::ExceptionOr<GC::Ref<ClassicScript>> fetch_a_classic_worker_imported_script(URL::URL const& url, HTML::EnvironmentSettingsObject& settings_object, PerformTheFetchHook perform_fetch)
  390. {
  391. auto& realm = settings_object.realm();
  392. auto& vm = realm.vm();
  393. // 1. Let response be null.
  394. IGNORE_USE_IN_ESCAPING_LAMBDA GC::Ptr<Fetch::Infrastructure::Response> response = nullptr;
  395. // 2. Let bodyBytes be null.
  396. Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes;
  397. // 3. Let request be a new request whose URL is url, client is settingsObject, destination is "script", initiator type is "other",
  398. // parser metadata is "not parser-inserted", and whose use-URL-credentials flag is set.
  399. auto request = Fetch::Infrastructure::Request::create(vm);
  400. request->set_url(url);
  401. request->set_client(&settings_object);
  402. request->set_destination(Fetch::Infrastructure::Request::Destination::Script);
  403. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Other);
  404. request->set_parser_metadata(Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted);
  405. request->set_use_url_credentials(true);
  406. auto process_response_consume_body = [&response, &body_bytes](GC::Ref<Fetch::Infrastructure::Response> res, Fetch::Infrastructure::FetchAlgorithms::BodyBytes bb) {
  407. // 1. Set bodyBytes to bb.
  408. body_bytes = move(bb);
  409. // 2. Set response to res.
  410. response = res;
  411. };
  412. // 4. If performFetch was given, run performFetch with request, isTopLevel, and with processResponseConsumeBody as defined below.
  413. if (perform_fetch) {
  414. TRY(perform_fetch->function()(request, TopLevelModule::Yes, move(process_response_consume_body)));
  415. }
  416. // Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.
  417. else {
  418. Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  419. fetch_algorithms_input.process_response_consume_body = move(process_response_consume_body);
  420. TRY(Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(vm, move(fetch_algorithms_input))));
  421. }
  422. // 5. Pause until response is not null.
  423. // FIXME: Consider using a "response holder" to avoid needing to annotate response as IGNORE_USE_IN_ESCAPING_LAMBDA.
  424. auto& event_loop = settings_object.responsible_event_loop();
  425. event_loop.spin_until(GC::create_function(vm.heap(), [&]() -> bool {
  426. return response;
  427. }));
  428. // 6. Set response to response's unsafe response.
  429. response = response->unsafe_response();
  430. // 7. If any of the following are true:
  431. // - bodyBytes is null or failure;
  432. // - response's status is not an ok status; or
  433. // - the result of extracting a MIME type from response's header list is not a JavaScript MIME type,
  434. // then throw a "NetworkError" DOMException.
  435. if (body_bytes.template has<Empty>() || body_bytes.template has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>()
  436. || !Fetch::Infrastructure::is_ok_status(response->status())
  437. || !response->header_list()->extract_mime_type().has_value() || !response->header_list()->extract_mime_type()->is_javascript()) {
  438. return WebIDL::NetworkError::create(realm, "Network error"_string);
  439. }
  440. // 8. Let sourceText be the result of UTF-8 decoding bodyBytes.
  441. auto decoder = TextCodec::decoder_for("UTF-8"sv);
  442. VERIFY(decoder.has_value());
  443. auto source_text = TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, body_bytes.get<ByteBuffer>()).release_value_but_fixme_should_propagate_errors();
  444. // 9. Let mutedErrors be true if response was CORS-cross-origin, and false otherwise.
  445. auto muted_errors = response->is_cors_cross_origin() ? ClassicScript::MutedErrors::Yes : ClassicScript::MutedErrors::No;
  446. // 10. Let script be the result of creating a classic script given sourceText, settingsObject's realm, response's URL, the default classic script fetch options, and mutedErrors.
  447. auto response_url = response->url().value_or({});
  448. auto script = ClassicScript::create(response_url.to_byte_string(), source_text, settings_object.realm(), response_url, 1, muted_errors);
  449. // 11. Return script.
  450. return script;
  451. }
  452. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-worker-script-tree
  453. WebIDL::ExceptionOr<void> fetch_module_worker_script_graph(URL::URL const& url, EnvironmentSettingsObject& fetch_client, Fetch::Infrastructure::Request::Destination destination, EnvironmentSettingsObject& settings_object, PerformTheFetchHook perform_fetch, OnFetchScriptComplete on_complete)
  454. {
  455. return fetch_worklet_module_worker_script_graph(url, fetch_client, destination, settings_object, move(perform_fetch), move(on_complete));
  456. }
  457. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-worklet/module-worker-script-graph
  458. // https://whatpr.org/html/9893/webappapis.html#fetch-a-worklet/module-worker-script-graph
  459. WebIDL::ExceptionOr<void> fetch_worklet_module_worker_script_graph(URL::URL const& url, EnvironmentSettingsObject& fetch_client, Fetch::Infrastructure::Request::Destination destination, EnvironmentSettingsObject& settings_object, PerformTheFetchHook perform_fetch, OnFetchScriptComplete on_complete)
  460. {
  461. auto& realm = settings_object.realm();
  462. auto& vm = realm.vm();
  463. // 1. Let options be a script fetch options whose cryptographic nonce is the empty string,
  464. // integrity metadata is the empty string, parser metadata is "not-parser-inserted",
  465. // credentials mode is credentialsMode, referrer policy is the empty string, and fetch priority is "auto".
  466. // FIXME: credentialsMode
  467. auto options = ScriptFetchOptions {
  468. .cryptographic_nonce = String {},
  469. .integrity_metadata = String {},
  470. .parser_metadata = Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted,
  471. .credentials_mode = Fetch::Infrastructure::Request::CredentialsMode::SameOrigin,
  472. .referrer_policy = ReferrerPolicy::ReferrerPolicy::EmptyString,
  473. .fetch_priority = Fetch::Infrastructure::Request::Priority::Auto
  474. };
  475. // onSingleFetchComplete given result is the following algorithm:
  476. auto on_single_fetch_complete = create_on_fetch_script_complete(vm.heap(), [&realm, &fetch_client, destination, perform_fetch = perform_fetch, on_complete = move(on_complete)](auto result) mutable {
  477. // 1. If result is null, run onComplete with null, and abort these steps.
  478. if (!result) {
  479. dbgln("on single fetch complete with nool");
  480. on_complete->function()(nullptr);
  481. return;
  482. }
  483. // 2. Fetch the descendants of and link result given fetchClient, destination, and onComplete. If performFetch was given, pass it along as well.
  484. fetch_descendants_of_and_link_a_module_script(realm, verify_cast<JavaScriptModuleScript>(*result), fetch_client, destination, move(perform_fetch), on_complete);
  485. });
  486. // 2. Fetch a single module script given url, fetchClient, destination, options, settingsObject's realm, "client", true,
  487. // and onSingleFetchComplete as defined below. If performFetch was given, pass it along as well.
  488. fetch_single_module_script(realm, url, fetch_client, destination, options, settings_object.realm(), Fetch::Infrastructure::Request::Referrer::Client, {}, TopLevelModule::Yes, move(perform_fetch), on_single_fetch_complete);
  489. return {};
  490. }
  491. // https://html.spec.whatwg.org/multipage/webappapis.html#internal-module-script-graph-fetching-procedure
  492. void fetch_internal_module_script_graph(JS::Realm& realm, JS::ModuleRequest const& module_request, EnvironmentSettingsObject& fetch_client_settings_object, Fetch::Infrastructure::Request::Destination destination, ScriptFetchOptions const& options, Script& referring_script, HashTable<ModuleLocationTuple> const& visited_set, PerformTheFetchHook perform_fetch, OnFetchScriptComplete on_complete)
  493. {
  494. // 1. Let url be the result of resolving a module specifier given referringScript and moduleRequest.[[Specifier]].
  495. auto url = MUST(resolve_module_specifier(referring_script, module_request.module_specifier));
  496. // 2. Assert: the previous step never throws an exception, because resolving a module specifier must have been previously successful with these same two arguments.
  497. // NOTE: Handled by MUST above.
  498. // 3. Let moduleType be the result of running the module type from module request steps given moduleRequest.
  499. auto module_type = module_type_from_module_request(module_request);
  500. // 4. Assert: visited set contains (url, moduleType).
  501. VERIFY(visited_set.contains({ url, module_type }));
  502. // onSingleFetchComplete given result is the following algorithm:
  503. auto on_single_fetch_complete = create_on_fetch_script_complete(realm.heap(), [&realm, perform_fetch, on_complete, &fetch_client_settings_object, destination, visited_set](auto result) mutable {
  504. // 1. If result is null, run onComplete with null, and abort these steps.
  505. if (!result) {
  506. on_complete->function()(nullptr);
  507. return;
  508. }
  509. // 2. Fetch the descendants of result given fetch client settings object, destination, visited set, and with onComplete. If performFetch was given, pass it along as well.
  510. auto& module_script = verify_cast<JavaScriptModuleScript>(*result);
  511. fetch_descendants_of_a_module_script(realm, module_script, fetch_client_settings_object, destination, visited_set, perform_fetch, on_complete);
  512. });
  513. // 5. Fetch a single module script given url, fetch client settings object, destination, options, referringScript's settings object's realm,
  514. // referringScript's base URL, moduleRequest, false, and onSingleFetchComplete as defined below. If performFetch was given, pass it along as well.
  515. fetch_single_module_script(realm, url, fetch_client_settings_object, destination, options, referring_script.realm(), referring_script.base_url(), module_request, TopLevelModule::No, perform_fetch, on_single_fetch_complete);
  516. }
  517. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-the-descendants-of-a-module-script
  518. void fetch_descendants_of_a_module_script(JS::Realm& realm, JavaScriptModuleScript& module_script, EnvironmentSettingsObject& fetch_client_settings_object, Fetch::Infrastructure::Request::Destination destination, HashTable<ModuleLocationTuple> visited_set, PerformTheFetchHook perform_fetch, OnFetchScriptComplete on_complete)
  519. {
  520. // 1. If module script's record is null, run onComplete with module script and return.
  521. if (!module_script.record()) {
  522. on_complete->function()(&module_script);
  523. return;
  524. }
  525. // 2. Let record be module script's record.
  526. auto const& record = module_script.record();
  527. // 3. If record is not a Cyclic Module Record, or if record.[[RequestedModules]] is empty, run onComplete with module script and return.
  528. // FIXME: Currently record is always a cyclic module.
  529. if (record->requested_modules().is_empty()) {
  530. on_complete->function()(&module_script);
  531. return;
  532. }
  533. // 4. Let moduleRequests be a new empty list.
  534. Vector<JS::ModuleRequest> module_requests;
  535. // 5. For each ModuleRequest Record requested of record.[[RequestedModules]],
  536. for (auto const& requested : record->requested_modules()) {
  537. // 1. Let url be the result of resolving a module specifier given module script and requested.[[Specifier]].
  538. auto url = MUST(resolve_module_specifier(module_script, requested.module_specifier));
  539. // 2. Assert: the previous step never throws an exception, because resolving a module specifier must have been previously successful with these same two arguments.
  540. // NOTE: Handled by MUST above.
  541. // 3. Let moduleType be the result of running the module type from module request steps given requested.
  542. auto module_type = module_type_from_module_request(requested);
  543. // 4. If visited set does not contain (url, moduleType), then:
  544. if (!visited_set.contains({ url, module_type })) {
  545. // 1. Append requested to moduleRequests.
  546. module_requests.append(requested);
  547. // 2. Append (url, moduleType) to visited set.
  548. visited_set.set({ url, module_type });
  549. }
  550. }
  551. // FIXME: 6. Let options be the descendant script fetch options for module script's fetch options.
  552. ScriptFetchOptions options;
  553. // FIXME: 7. Assert: options is not null, as module script is a JavaScript module script.
  554. // 8. Let pendingCount be the length of moduleRequests.
  555. auto pending_count = module_requests.size();
  556. // 9. If pendingCount is zero, run onComplete with module script.
  557. if (pending_count == 0) {
  558. on_complete->function()(&module_script);
  559. return;
  560. }
  561. // 10. Let failed be false.
  562. bool failed = false;
  563. // 11. For each moduleRequest in moduleRequests, perform the internal module script graph fetching procedure given moduleRequest,
  564. // fetch client settings object, destination, options, module script, visited set, and onInternalFetchingComplete as defined below.
  565. // If performFetch was given, pass it along as well.
  566. for (auto const& module_request : module_requests) {
  567. // onInternalFetchingComplete given result is the following algorithm:
  568. auto on_internal_fetching_complete = create_on_fetch_script_complete(realm.heap(), [failed, pending_count, &module_script, on_complete](auto result) mutable {
  569. // 1. If failed is true, then abort these steps.
  570. if (failed)
  571. return;
  572. // 2. If result is null, then set failed to true, run onComplete with null, and abort these steps.
  573. if (!result) {
  574. failed = true;
  575. on_complete->function()(nullptr);
  576. return;
  577. }
  578. // 3. Assert: pendingCount is greater than zero.
  579. VERIFY(pending_count > 0);
  580. // 4. Decrement pendingCount by one.
  581. --pending_count;
  582. // 5. If pendingCount is zero, run onComplete with module script.
  583. if (pending_count == 0)
  584. on_complete->function()(&module_script);
  585. });
  586. fetch_internal_module_script_graph(realm, module_request, fetch_client_settings_object, destination, options, module_script, visited_set, perform_fetch, on_internal_fetching_complete);
  587. }
  588. }
  589. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-destination-from-module-type
  590. Fetch::Infrastructure::Request::Destination fetch_destination_from_module_type(Fetch::Infrastructure::Request::Destination default_destination, ByteString const& module_type)
  591. {
  592. // 1. If moduleType is "json", then return "json".
  593. if (module_type == "json"sv)
  594. return Fetch::Infrastructure::Request::Destination::JSON;
  595. // 2. If moduleType is "css", then return "style".
  596. if (module_type == "css"sv)
  597. return Fetch::Infrastructure::Request::Destination::Style;
  598. // 3. Return defaultDestination.
  599. return default_destination;
  600. }
  601. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
  602. // https://whatpr.org/html/9893/webappapis.html#fetch-a-single-module-script
  603. void fetch_single_module_script(JS::Realm& realm,
  604. URL::URL const& url,
  605. EnvironmentSettingsObject& fetch_client,
  606. Fetch::Infrastructure::Request::Destination destination,
  607. ScriptFetchOptions const& options,
  608. JS::Realm& module_map_realm,
  609. Web::Fetch::Infrastructure::Request::ReferrerType const& referrer,
  610. Optional<JS::ModuleRequest> const& module_request,
  611. TopLevelModule is_top_level,
  612. PerformTheFetchHook perform_fetch,
  613. OnFetchScriptComplete on_complete)
  614. {
  615. // 1. Let moduleType be "javascript".
  616. ByteString module_type = "javascript"sv;
  617. // 2. If moduleRequest was given, then set moduleType to the result of running the module type from module request steps given moduleRequest.
  618. if (module_request.has_value())
  619. module_type = module_type_from_module_request(*module_request);
  620. // 3. Assert: the result of running the module type allowed steps given moduleType and moduleMapRealm is true.
  621. // Otherwise we would not have reached this point because a failure would have been raised when inspecting moduleRequest.[[Assertions]]
  622. // in create a JavaScript module script or fetch a single imported module script.
  623. VERIFY(module_type_allowed(module_map_realm, module_type));
  624. // 4. Let moduleMap be moduleMapRealm's module map.
  625. auto& module_map = module_map_of_realm(module_map_realm);
  626. // 5. If moduleMap[(url, moduleType)] is "fetching", wait in parallel until that entry's value changes,
  627. // then queue a task on the networking task source to proceed with running the following steps.
  628. if (module_map.is_fetching(url, module_type)) {
  629. module_map.wait_for_change(realm.heap(), url, module_type, [on_complete, &realm](auto entry) -> void {
  630. HTML::queue_global_task(HTML::Task::Source::Networking, realm.global_object(), GC::create_function(realm.heap(), [on_complete, entry] {
  631. // FIXME: This should run other steps, for now we just assume the script loaded.
  632. VERIFY(entry.type == ModuleMap::EntryType::ModuleScript || entry.type == ModuleMap::EntryType::Failed);
  633. on_complete->function()(entry.module_script);
  634. }));
  635. });
  636. return;
  637. }
  638. // 6. If moduleMap[(url, moduleType)] exists, run onComplete given moduleMap[(url, moduleType)], and return.
  639. auto entry = module_map.get(url, module_type);
  640. if (entry.has_value() && entry->type == ModuleMap::EntryType::ModuleScript) {
  641. on_complete->function()(entry->module_script);
  642. return;
  643. }
  644. // 7. Set moduleMap[(url, moduleType)] to "fetching".
  645. module_map.set(url, module_type, { ModuleMap::EntryType::Fetching, nullptr });
  646. // 8. Let request be a new request whose URL is url, mode is "cors", referrer is referrer, and client is fetchClient.
  647. auto request = Fetch::Infrastructure::Request::create(realm.vm());
  648. request->set_url(url);
  649. request->set_mode(Fetch::Infrastructure::Request::Mode::CORS);
  650. request->set_referrer(referrer);
  651. request->set_client(&fetch_client);
  652. // 9. Set request's destination to the result of running the fetch destination from module type steps given destination and moduleType.
  653. request->set_destination(fetch_destination_from_module_type(destination, module_type));
  654. // 10. If destination is "worker", "sharedworker", or "serviceworker", and isTopLevel is true, then set request's mode to "same-origin".
  655. if ((destination == Fetch::Infrastructure::Request::Destination::Worker || destination == Fetch::Infrastructure::Request::Destination::SharedWorker || destination == Fetch::Infrastructure::Request::Destination::ServiceWorker) && is_top_level == TopLevelModule::Yes)
  656. request->set_mode(Fetch::Infrastructure::Request::Mode::SameOrigin);
  657. // 11. Set request's initiator type to "script".
  658. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Script);
  659. // 12. Set up the module script request given request and options.
  660. set_up_module_script_request(request, options);
  661. // 13. If performFetch was given, run performFetch with request, isTopLevel, and with processResponseConsumeBody as defined below.
  662. // Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.
  663. // In both cases, let processResponseConsumeBody given response response and null, failure, or a byte sequence bodyBytes be the following algorithm:
  664. auto process_response_consume_body = [&module_map, url, module_type, &module_map_realm, on_complete](GC::Ref<Fetch::Infrastructure::Response> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {
  665. // 1. If either of the following conditions are met:
  666. // - bodyBytes is null or failure; or
  667. // - response's status is not an ok status,
  668. if (body_bytes.has<Empty>() || body_bytes.has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>() || !Fetch::Infrastructure::is_ok_status(response->status())) {
  669. // then set moduleMap[(url, moduleType)] to null, run onComplete given null, and abort these steps.
  670. module_map.set(url, module_type, { ModuleMap::EntryType::Failed, nullptr });
  671. on_complete->function()(nullptr);
  672. return;
  673. }
  674. // 2. Let sourceText be the result of UTF-8 decoding bodyBytes.
  675. auto decoder = TextCodec::decoder_for("UTF-8"sv);
  676. VERIFY(decoder.has_value());
  677. auto source_text = TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, body_bytes.get<ByteBuffer>()).release_value_but_fixme_should_propagate_errors();
  678. // 3. Let mimeType be the result of extracting a MIME type from response's header list.
  679. auto mime_type = response->header_list()->extract_mime_type();
  680. // 4. Let moduleScript be null.
  681. GC::Ptr<JavaScriptModuleScript> module_script;
  682. // FIXME: 5. Let referrerPolicy be the result of parsing the `Referrer-Policy` header given response. [REFERRERPOLICY]
  683. // FIXME: 6. If referrerPolicy is not the empty string, set options's referrer policy to referrerPolicy.
  684. // 7. If mimeType is a JavaScript MIME type and moduleType is "javascript", then set moduleScript to the result of creating a JavaScript module script given sourceText, moduleMapRealm, response's URL, and options.
  685. // FIXME: Pass options.
  686. if (mime_type->is_javascript() && module_type == "javascript")
  687. module_script = JavaScriptModuleScript::create(url.basename(), source_text, module_map_realm, response->url().value_or({})).release_value_but_fixme_should_propagate_errors();
  688. // FIXME: 8. If the MIME type essence of mimeType is "text/css" and moduleType is "css", then set moduleScript to the result of creating a CSS module script given sourceText and settingsObject.
  689. // FIXME: 9. If mimeType is a JSON MIME type and moduleType is "json", then set moduleScript to the result of creating a JSON module script given sourceText and settingsObject.
  690. // 10. Set moduleMap[(url, moduleType)] to moduleScript, and run onComplete given moduleScript.
  691. module_map.set(url, module_type, { ModuleMap::EntryType::ModuleScript, module_script });
  692. on_complete->function()(module_script);
  693. };
  694. if (perform_fetch != nullptr) {
  695. perform_fetch->function()(request, is_top_level, move(process_response_consume_body)).release_value_but_fixme_should_propagate_errors();
  696. } else {
  697. Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  698. fetch_algorithms_input.process_response_consume_body = move(process_response_consume_body);
  699. Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(realm.vm(), move(fetch_algorithms_input))).release_value_but_fixme_should_propagate_errors();
  700. }
  701. }
  702. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-script-tree
  703. // https://whatpr.org/html/9893/webappapis.html#fetch-a-module-script-tree
  704. void fetch_external_module_script_graph(JS::Realm& realm, URL::URL const& url, EnvironmentSettingsObject& settings_object, ScriptFetchOptions const& options, OnFetchScriptComplete on_complete)
  705. {
  706. auto steps = create_on_fetch_script_complete(realm.heap(), [&realm, &settings_object, on_complete, url](auto result) mutable {
  707. // 1. If result is null, run onComplete given null, and abort these steps.
  708. if (!result) {
  709. on_complete->function()(nullptr);
  710. return;
  711. }
  712. // 2. Fetch the descendants of and link result given settingsObject, "script", and onComplete.
  713. auto& module_script = verify_cast<JavaScriptModuleScript>(*result);
  714. fetch_descendants_of_and_link_a_module_script(realm, module_script, settings_object, Fetch::Infrastructure::Request::Destination::Script, nullptr, on_complete);
  715. });
  716. // 1. Fetch a single module script given url, settingsObject, "script", options, settingsObject's realm, "client", true, and with the following steps given result:
  717. fetch_single_module_script(realm, url, settings_object, Fetch::Infrastructure::Request::Destination::Script, options, settings_object.realm(), Web::Fetch::Infrastructure::Request::Referrer::Client, {}, TopLevelModule::Yes, nullptr, steps);
  718. }
  719. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-an-inline-module-script-graph
  720. void fetch_inline_module_script_graph(JS::Realm& realm, ByteString const& filename, ByteString const& source_text, URL::URL const& base_url, EnvironmentSettingsObject& settings_object, OnFetchScriptComplete on_complete)
  721. {
  722. // 1. Let script be the result of creating a JavaScript module script using sourceText, settingsObject's realm, baseURL, and options.
  723. auto script = JavaScriptModuleScript::create(filename, source_text.view(), settings_object.realm(), base_url).release_value_but_fixme_should_propagate_errors();
  724. // 2. Fetch the descendants of and link script, given settingsObject, "script", and onComplete.
  725. fetch_descendants_of_and_link_a_module_script(realm, *script, settings_object, Fetch::Infrastructure::Request::Destination::Script, nullptr, on_complete);
  726. }
  727. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-imported-module-script
  728. void fetch_single_imported_module_script(JS::Realm& realm,
  729. URL::URL const& url,
  730. EnvironmentSettingsObject& fetch_client,
  731. Fetch::Infrastructure::Request::Destination destination,
  732. ScriptFetchOptions const& options,
  733. JS::Realm& module_map_realm,
  734. Fetch::Infrastructure::Request::ReferrerType referrer,
  735. JS::ModuleRequest const& module_request,
  736. PerformTheFetchHook perform_fetch,
  737. OnFetchScriptComplete on_complete)
  738. {
  739. // 1. Assert: moduleRequest.[[Attributes]] does not contain any Record entry such that entry.[[Key]] is not "type",
  740. // because we only asked for "type" attributes in HostGetSupportedImportAttributes.
  741. for (auto const& entry : module_request.attributes)
  742. VERIFY(entry.key == "type"sv);
  743. // 2. Let moduleType be the result of running the module type from module request steps given moduleRequest.
  744. auto module_type = module_type_from_module_request(module_request);
  745. // 3. If the result of running the module type allowed steps given moduleType and moduleMapRealm is false,
  746. // then run onComplete given null, and return.
  747. if (!module_type_allowed(module_map_realm, module_type)) {
  748. on_complete->function()(nullptr);
  749. return;
  750. }
  751. // 4. Fetch a single module script given url, fetchClient, destination, options, moduleMapRealm, referrer, moduleRequest, false,
  752. // and onComplete. If performFetch was given, pass it along as well.
  753. fetch_single_module_script(realm, url, fetch_client, destination, options, module_map_realm, referrer, module_request, TopLevelModule::No, perform_fetch, on_complete);
  754. }
  755. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-the-descendants-of-and-link-a-module-script
  756. void fetch_descendants_of_and_link_a_module_script(JS::Realm& realm,
  757. JavaScriptModuleScript& module_script,
  758. EnvironmentSettingsObject& fetch_client,
  759. Fetch::Infrastructure::Request::Destination destination,
  760. PerformTheFetchHook perform_fetch,
  761. OnFetchScriptComplete on_complete)
  762. {
  763. // 1. Let record be moduleScript's record.
  764. auto* record = module_script.record();
  765. // 2. If record is null, then:
  766. if (!record) {
  767. // 1. Set moduleScript's error to rethrow to moduleScript's parse error.
  768. module_script.set_error_to_rethrow(module_script.parse_error());
  769. // 2. Run onComplete given moduleScript.
  770. on_complete->function()(module_script);
  771. // 3. Return.
  772. return;
  773. }
  774. // 3. Let state be Record { [[ParseError]]: null, [[Destination]]: destination, [[PerformFetch]]: null, [[FetchClient]]: fetchClient }.
  775. auto state = realm.heap().allocate<FetchContext>(JS::js_null(), destination, nullptr, fetch_client);
  776. // 4. If performFetch was given, set state.[[PerformFetch]] to performFetch.
  777. state->perform_fetch = perform_fetch;
  778. // FIXME: These should most likely be steps in the spec.
  779. // NOTE: For reasons beyond my understanding, we cannot use TemporaryExecutionContext here.
  780. // Calling perform_a_microtask_checkpoint() on the fetch_client's responsible_event_loop
  781. // prevents this from functioning properly. HTMLParser::the_end would be run before
  782. // HTMLScriptElement::prepare_script had a chance to setup the callback to mark_done properly,
  783. // resulting in the event loop hanging forever awaiting for the script to be ready for parser
  784. // execution.
  785. realm.vm().push_execution_context(fetch_client.realm_execution_context());
  786. prepare_to_run_callback(realm);
  787. // 5. Let loadingPromise be record.LoadRequestedModules(state).
  788. auto& loading_promise = record->load_requested_modules(state);
  789. // 6. Upon fulfillment of loadingPromise, run the following steps:
  790. WebIDL::upon_fulfillment(loading_promise, GC::create_function(realm.heap(), [&realm, record, &module_script, on_complete](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  791. // 1. Perform record.Link().
  792. auto linking_result = record->link(realm.vm());
  793. // If this throws an exception, set result's error to rethrow to that exception.
  794. if (linking_result.is_throw_completion())
  795. module_script.set_error_to_rethrow(linking_result.release_error().value().value());
  796. // 2. Run onComplete given moduleScript.
  797. on_complete->function()(module_script);
  798. return JS::js_undefined();
  799. }));
  800. // 7. Upon rejection of loadingPromise, run the following steps:
  801. WebIDL::upon_rejection(loading_promise, GC::create_function(realm.heap(), [state, &module_script, on_complete](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
  802. // 1. If state.[[ParseError]] is not null, set moduleScript's error to rethrow to state.[[ParseError]] and run
  803. // onComplete given moduleScript.
  804. if (!state->parse_error.is_null()) {
  805. module_script.set_error_to_rethrow(state->parse_error);
  806. on_complete->function()(module_script);
  807. }
  808. // 2. Otherwise, run onComplete given null.
  809. else {
  810. on_complete->function()(nullptr);
  811. }
  812. return JS::js_undefined();
  813. }));
  814. clean_up_after_running_callback(realm);
  815. realm.vm().pop_execution_context();
  816. }
  817. }