Fetching.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. /*
  2. * Copyright (c) 2022, networkException <networkexception@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/URLParser.h>
  7. #include <LibJS/Runtime/ModuleRequest.h>
  8. #include <LibTextCodec/Decoder.h>
  9. #include <LibWeb/DOM/Document.h>
  10. #include <LibWeb/Fetch/Fetching/Fetching.h>
  11. #include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
  12. #include <LibWeb/Fetch/Infrastructure/HTTP/Headers.h>
  13. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  14. #include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
  15. #include <LibWeb/HTML/HTMLScriptElement.h>
  16. #include <LibWeb/HTML/PotentialCORSRequest.h>
  17. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  18. #include <LibWeb/HTML/Scripting/Environments.h>
  19. #include <LibWeb/HTML/Scripting/Fetching.h>
  20. #include <LibWeb/HTML/Scripting/ModuleScript.h>
  21. #include <LibWeb/HTML/Window.h>
  22. #include <LibWeb/Infra/Strings.h>
  23. #include <LibWeb/Loader/LoadRequest.h>
  24. #include <LibWeb/Loader/ResourceLoader.h>
  25. #include <LibWeb/MimeSniff/MimeType.h>
  26. namespace Web::HTML {
  27. // https://html.spec.whatwg.org/multipage/webappapis.html#module-type-from-module-request
  28. DeprecatedString module_type_from_module_request(JS::ModuleRequest const& module_request)
  29. {
  30. // 1. Let moduleType be "javascript".
  31. DeprecatedString module_type = "javascript"sv;
  32. // 2. If moduleRequest.[[Assertions]] has a Record entry such that entry.[[Key]] is "type", then:
  33. for (auto const& entry : module_request.assertions) {
  34. if (entry.key != "type"sv)
  35. continue;
  36. // 1. If entry.[[Value]] is "javascript", then set moduleType to null.
  37. if (entry.value == "javascript"sv)
  38. module_type = nullptr;
  39. // 2. Otherwise, set moduleType to entry.[[Value]].
  40. else
  41. module_type = entry.value;
  42. }
  43. // 3. Return moduleType.
  44. return module_type;
  45. }
  46. // https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier
  47. WebIDL::ExceptionOr<AK::URL> resolve_module_specifier(Optional<Script&> referring_script, DeprecatedString const& specifier)
  48. {
  49. // 1. Let settingsObject and baseURL be null.
  50. Optional<EnvironmentSettingsObject&> settings_object;
  51. Optional<AK::URL const&> base_url;
  52. // 2. If referringScript is not null, then:
  53. if (referring_script.has_value()) {
  54. // 1. Set settingsObject to referringScript's settings object.
  55. settings_object = referring_script->settings_object();
  56. // 2. Set baseURL to referringScript's base URL.
  57. base_url = referring_script->base_url();
  58. }
  59. // 3. Otherwise:
  60. else {
  61. // 1. Assert: there is a current settings object.
  62. // NOTE: This is handled by the current_settings_object() accessor.
  63. // 2. Set settingsObject to the current settings object.
  64. settings_object = current_settings_object();
  65. // 3. Set baseURL to settingsObject's API base URL.
  66. base_url = settings_object->api_base_url();
  67. }
  68. // 4. Let importMap be an empty import map.
  69. ImportMap import_map;
  70. // 5. If settingsObject's global object implements Window, then set importMap to settingsObject's global object's import map.
  71. if (is<Window>(settings_object->global_object()))
  72. import_map = verify_cast<Window>(settings_object->global_object()).import_map();
  73. // 6. Let baseURLString be baseURL, serialized.
  74. auto base_url_string = base_url->serialize();
  75. // 7. Let asURL be the result of resolving a URL-like module specifier given specifier and baseURL.
  76. auto as_url = resolve_url_like_module_specifier(specifier, *base_url);
  77. // 8. Let normalizedSpecifier be the serialization of asURL, if asURL is non-null; otherwise, specifier.
  78. auto normalized_specifier = as_url.has_value() ? as_url->serialize() : specifier;
  79. // 9. For each scopePrefix → scopeImports of importMap's scopes:
  80. for (auto const& entry : import_map.scopes()) {
  81. // FIXME: Clarify if the serialization steps need to be run here. The steps below assume
  82. // scopePrefix to be a string.
  83. auto const& scope_prefix = entry.key.serialize();
  84. auto const& scope_imports = entry.value;
  85. // 1. If scopePrefix is baseURLString, or if scopePrefix ends with U+002F (/) and scopePrefix is a code unit prefix of baseURLString, then:
  86. if (scope_prefix == base_url_string || (scope_prefix.ends_with("/"sv) && Infra::is_code_unit_prefix(scope_prefix, base_url_string))) {
  87. // 1. Let scopeImportsMatch be the result of resolving an imports match given normalizedSpecifier, asURL, and scopeImports.
  88. auto scope_imports_match = TRY(resolve_imports_match(normalized_specifier, as_url, scope_imports));
  89. // 2. If scopeImportsMatch is not null, then return scopeImportsMatch.
  90. if (scope_imports_match.has_value())
  91. return scope_imports_match.release_value();
  92. }
  93. }
  94. // 10. Let topLevelImportsMatch be the result of resolving an imports match given normalizedSpecifier, asURL, and importMap's imports.
  95. auto top_level_imports_match = TRY(resolve_imports_match(normalized_specifier, as_url, import_map.imports()));
  96. // 11. If topLevelImportsMatch is not null, then return topLevelImportsMatch.
  97. if (top_level_imports_match.has_value())
  98. return top_level_imports_match.release_value();
  99. // 12. If asURL is not null, then return asURL.
  100. if (as_url.has_value())
  101. return as_url.release_value();
  102. // 13. Throw a TypeError indicating that specifier was a bare specifier, but was not remapped to anything by importMap.
  103. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("Failed to resolve non relative module specifier '{}' from an import map.", specifier).release_value_but_fixme_should_propagate_errors() };
  104. }
  105. // https://html.spec.whatwg.org/multipage/webappapis.html#resolving-an-imports-match
  106. WebIDL::ExceptionOr<Optional<AK::URL>> resolve_imports_match(DeprecatedString const& normalized_specifier, Optional<AK::URL> as_url, ModuleSpecifierMap const& specifier_map)
  107. {
  108. // 1. For each specifierKey → resolutionResult of specifierMap:
  109. for (auto const& [specifier_key, resolution_result] : specifier_map) {
  110. // 1. If specifierKey is normalizedSpecifier, then:
  111. if (specifier_key == normalized_specifier) {
  112. // 1. If resolutionResult is null, then throw a TypeError indicating that resolution of specifierKey was blocked by a null entry.
  113. if (!resolution_result.has_value())
  114. 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() };
  115. // 2. Assert: resolutionResult is a URL.
  116. VERIFY(resolution_result->is_valid());
  117. // 3. Return resolutionResult.
  118. return resolution_result;
  119. }
  120. // 2. If all of the following are true:
  121. if (
  122. // - specifierKey ends with U+002F (/);
  123. specifier_key.ends_with("/"sv) &&
  124. // - specifierKey is a code unit prefix of normalizedSpecifier; and
  125. Infra::is_code_unit_prefix(specifier_key, normalized_specifier) &&
  126. // - either asURL is null, or asURL is special,
  127. (!as_url.has_value() || as_url->is_special())
  128. // then:
  129. ) {
  130. // 1. If resolutionResult is null, then throw a TypeError indicating that the resolution of specifierKey was blocked by a null entry.
  131. if (!resolution_result.has_value())
  132. 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() };
  133. // 2. Assert: resolutionResult is a URL.
  134. VERIFY(resolution_result->is_valid());
  135. // 3. Let afterPrefix be the portion of normalizedSpecifier after the initial specifierKey prefix.
  136. // FIXME: Clarify if this is meant by the portion after the initial specifierKey prefix.
  137. auto after_prefix = normalized_specifier.substring(specifier_key.length());
  138. // 4. Assert: resolutionResult, serialized, ends with U+002F (/), as enforced during parsing.
  139. VERIFY(resolution_result->serialize().ends_with("/"sv));
  140. // 5. Let url be the result of URL parsing afterPrefix with resolutionResult.
  141. auto url = URLParser::parse(after_prefix, *resolution_result);
  142. // 6. If url is failure, then throw a TypeError indicating that resolution of normalizedSpecifier was blocked since the afterPrefix portion
  143. // could not be URL-parsed relative to the resolutionResult mapped to by the specifierKey prefix.
  144. if (!url.is_valid())
  145. 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() };
  146. // 7. Assert: url is a URL.
  147. VERIFY(url.is_valid());
  148. // 8. If the serialization of resolutionResult is not a code unit prefix of the serialization of url, then throw a TypeError indicating
  149. // that the resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.
  150. if (!Infra::is_code_unit_prefix(resolution_result->serialize(), url.serialize()))
  151. 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() };
  152. // 9. Return url.
  153. return url;
  154. }
  155. }
  156. // 2. Return null.
  157. return Optional<AK::URL> {};
  158. }
  159. // https://html.spec.whatwg.org/multipage/webappapis.html#resolving-a-url-like-module-specifier
  160. Optional<AK::URL> resolve_url_like_module_specifier(DeprecatedString const& specifier, AK::URL const& base_url)
  161. {
  162. // 1. If specifier starts with "/", "./", or "../", then:
  163. if (specifier.starts_with("/"sv) || specifier.starts_with("./"sv) || specifier.starts_with("../"sv)) {
  164. // 1. Let url be the result of URL parsing specifier with baseURL.
  165. auto url = URLParser::parse(specifier, base_url);
  166. // 2. If url is failure, then return null.
  167. if (!url.is_valid())
  168. return {};
  169. // 3. Return url.
  170. return url;
  171. }
  172. // 2. Let url be the result of URL parsing specifier (with no base URL).
  173. auto url = URLParser::parse(specifier);
  174. // 3. If url is failure, then return null.
  175. if (!url.is_valid())
  176. return {};
  177. // 4. Return url.
  178. return url;
  179. }
  180. // https://html.spec.whatwg.org/multipage/webappapis.html#set-up-the-classic-script-request
  181. static void set_up_classic_script_request(Fetch::Infrastructure::Request& request, ScriptFetchOptions const& options)
  182. {
  183. // Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's
  184. // integrity metadata, its parser metadata to options's parser metadata, its referrer policy to options's referrer
  185. // policy, its render-blocking to options's render-blocking, and its priority to options's fetch priority.
  186. request.set_cryptographic_nonce_metadata(options.cryptographic_nonce);
  187. request.set_integrity_metadata(options.integrity_metadata);
  188. request.set_parser_metadata(options.parser_metadata);
  189. request.set_referrer_policy(options.referrer_policy);
  190. request.set_render_blocking(options.render_blocking);
  191. request.set_priority(options.fetch_priority);
  192. }
  193. class ClassicScriptResponseHandler final : public RefCounted<ClassicScriptResponseHandler> {
  194. public:
  195. ClassicScriptResponseHandler(JS::NonnullGCPtr<HTMLScriptElement> element, EnvironmentSettingsObject& settings_object, ScriptFetchOptions options, String character_encoding, OnFetchScriptComplete on_complete)
  196. : m_element(element)
  197. , m_settings_object(settings_object)
  198. , m_options(move(options))
  199. , m_character_encoding(move(character_encoding))
  200. , m_on_complete(move(on_complete))
  201. {
  202. }
  203. // https://html.spec.whatwg.org/multipage/webappapis.html#fetching-scripts:concept-fetch-4
  204. void process_response(JS::NonnullGCPtr<Fetch::Infrastructure::Response> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes)
  205. {
  206. // 1. Set response to response's unsafe response.
  207. response = response->unsafe_response();
  208. // 2. If either of the following conditions are met:
  209. // - bodyBytes is null or failure; or
  210. // - response's status is not an ok status,
  211. if (body_bytes.template has<Empty>() || body_bytes.template has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>() || !Fetch::Infrastructure::is_ok_status(response->status())) {
  212. // then run onComplete given null, and abort these steps.
  213. m_on_complete(nullptr);
  214. return;
  215. }
  216. // 3. Let potentialMIMETypeForEncoding be the result of extracting a MIME type given response's header list.
  217. auto potential_mime_type_for_encoding = response->header_list()->extract_mime_type().release_value_but_fixme_should_propagate_errors();
  218. // 4. Set character encoding to the result of legacy extracting an encoding given potentialMIMETypeForEncoding
  219. // and character encoding.
  220. auto character_encoding = Fetch::Infrastructure::legacy_extract_an_encoding(potential_mime_type_for_encoding, m_character_encoding);
  221. // 5. Let source text be the result of decoding bodyBytes to Unicode, using character encoding as the fallback
  222. // encoding.
  223. auto fallback_decoder = TextCodec::decoder_for(character_encoding);
  224. VERIFY(fallback_decoder.has_value());
  225. 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();
  226. // 6. Let muted errors be true if response was CORS-cross-origin, and false otherwise.
  227. auto muted_errors = response->is_cors_cross_origin() ? ClassicScript::MutedErrors::Yes : ClassicScript::MutedErrors::No;
  228. // 7. Let script be the result of creating a classic script given source text, settings object, response's URL,
  229. // options, and muted errors.
  230. // FIXME: Pass options.
  231. auto script = ClassicScript::create(m_element->document().url().to_deprecated_string(), source_text, *m_settings_object, response->url().value_or({}), 1, muted_errors);
  232. // 8. Run onComplete given script.
  233. m_on_complete(script);
  234. }
  235. private:
  236. JS::Handle<HTMLScriptElement> m_element;
  237. JS::Handle<EnvironmentSettingsObject> m_settings_object;
  238. ScriptFetchOptions m_options;
  239. String m_character_encoding;
  240. OnFetchScriptComplete m_on_complete;
  241. };
  242. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-script
  243. WebIDL::ExceptionOr<void> fetch_classic_script(JS::NonnullGCPtr<HTMLScriptElement> element, AK::URL const& url, EnvironmentSettingsObject& settings_object, ScriptFetchOptions options, CORSSettingAttribute cors_setting, String character_encoding, OnFetchScriptComplete on_complete)
  244. {
  245. auto& realm = element->realm();
  246. auto& vm = realm.vm();
  247. // 1. Let request be the result of creating a potential-CORS request given url, "script", and CORS setting.
  248. auto request = create_potential_CORS_request(vm, url, Fetch::Infrastructure::Request::Destination::Script, cors_setting);
  249. // 2. Set request's client to settings object.
  250. request->set_client(&settings_object);
  251. // 3. Set request's initiator type to "script".
  252. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Script);
  253. // 4. Set up the classic script request given request and options.
  254. set_up_classic_script_request(*request, options);
  255. // 5. Fetch request with the following processResponseConsumeBody steps given response response and null, failure,
  256. // or a byte sequence bodyBytes:
  257. auto response_handler = make_ref_counted<ClassicScriptResponseHandler>(element, settings_object, move(options), move(character_encoding), move(on_complete));
  258. Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  259. fetch_algorithms_input.process_response_consume_body = [&realm, response_handler = move(response_handler)](auto response, auto body_bytes) {
  260. // FIXME: See HTMLLinkElement::default_fetch_and_process_linked_resource for thorough notes on the workaround
  261. // added here for CORS cross-origin responses. The gist is that all cross-origin responses will have a
  262. // null bodyBytes. So we must read the actual body from the unsafe response.
  263. // https://github.com/whatwg/html/issues/9066
  264. if (response->is_cors_cross_origin() && body_bytes.template has<Empty>() && response->unsafe_response()->body().has_value()) {
  265. auto process_body = [response, response_handler](auto bytes) {
  266. response_handler->process_response(response, move(bytes));
  267. };
  268. auto process_body_error = [response, response_handler](auto) {
  269. response_handler->process_response(response, Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag {});
  270. };
  271. response->unsafe_response()->body()->fully_read(realm, move(process_body), move(process_body_error), JS::NonnullGCPtr { realm.global_object() }).release_value_but_fixme_should_propagate_errors();
  272. } else {
  273. response_handler->process_response(response, move(body_bytes));
  274. }
  275. };
  276. TRY(Fetch::Fetching::fetch(element->realm(), request, Fetch::Infrastructure::FetchAlgorithms::create(vm, move(fetch_algorithms_input))));
  277. return {};
  278. }
  279. // https://html.spec.whatwg.org/multipage/webappapis.html#internal-module-script-graph-fetching-procedure
  280. void fetch_internal_module_script_graph(JS::ModuleRequest const& module_request, EnvironmentSettingsObject& fetch_client_settings_object, StringView destination, Script& referring_script, HashTable<ModuleLocationTuple> const& visited_set, OnFetchScriptComplete on_complete)
  281. {
  282. // 1. Let url be the result of resolving a module specifier given referringScript and moduleRequest.[[Specifier]].
  283. auto url = MUST(resolve_module_specifier(referring_script, module_request.module_specifier));
  284. // 2. Assert: the previous step never throws an exception, because resolving a module specifier must have been previously successful with these same two arguments.
  285. // NOTE: Handled by MUST above.
  286. // 3. Let moduleType be the result of running the module type from module request steps given moduleRequest.
  287. auto module_type = module_type_from_module_request(module_request);
  288. // 4. Assert: visited set contains (url, moduleType).
  289. VERIFY(visited_set.contains({ url, module_type }));
  290. // 5. Fetch a single module script given url, fetch client settings object, destination, options, referringScript's settings object,
  291. // referringScript's base URL, moduleRequest, false, and onSingleFetchComplete as defined below. If performFetch was given, pass it along as well.
  292. // FIXME: Pass options and performFetch if given.
  293. fetch_single_module_script(url, fetch_client_settings_object, destination, referring_script.settings_object(), referring_script.base_url(), module_request, TopLevelModule::No, [on_complete = move(on_complete), &fetch_client_settings_object, destination, visited_set](auto result) mutable {
  294. // onSingleFetchComplete given result is the following algorithm:
  295. // 1. If result is null, run onComplete with null, and abort these steps.
  296. if (!result) {
  297. on_complete(nullptr);
  298. return;
  299. }
  300. // 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.
  301. // FIXME: Pass performFetch if given.
  302. auto& module_script = verify_cast<JavaScriptModuleScript>(*result);
  303. fetch_descendants_of_a_module_script(module_script, fetch_client_settings_object, destination, visited_set, move(on_complete));
  304. });
  305. }
  306. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-the-descendants-of-a-module-script
  307. void fetch_descendants_of_a_module_script(JavaScriptModuleScript& module_script, EnvironmentSettingsObject& fetch_client_settings_object, StringView destination, HashTable<ModuleLocationTuple> visited_set, OnFetchScriptComplete on_complete)
  308. {
  309. // 1. If module script's record is null, run onComplete with module script and return.
  310. if (!module_script.record()) {
  311. on_complete(&module_script);
  312. return;
  313. }
  314. // 2. Let record be module script's record.
  315. auto const& record = module_script.record();
  316. // 3. If record is not a Cyclic Module Record, or if record.[[RequestedModules]] is empty, run onComplete with module script and return.
  317. // FIXME: Currently record is always a cyclic module.
  318. if (record->requested_modules().is_empty()) {
  319. on_complete(&module_script);
  320. return;
  321. }
  322. // 4. Let moduleRequests be a new empty list.
  323. Vector<JS::ModuleRequest> module_requests;
  324. // 5. For each ModuleRequest Record requested of record.[[RequestedModules]],
  325. for (auto const& requested : record->requested_modules()) {
  326. // 1. Let url be the result of resolving a module specifier given module script and requested.[[Specifier]].
  327. auto url = MUST(resolve_module_specifier(module_script, requested.module_specifier));
  328. // 2. Assert: the previous step never throws an exception, because resolving a module specifier must have been previously successful with these same two arguments.
  329. // NOTE: Handled by MUST above.
  330. // 3. Let moduleType be the result of running the module type from module request steps given requested.
  331. auto module_type = module_type_from_module_request(requested);
  332. // 4. If visited set does not contain (url, moduleType), then:
  333. if (!visited_set.contains({ url, module_type })) {
  334. // 1. Append requested to moduleRequests.
  335. module_requests.append(requested);
  336. // 2. Append (url, moduleType) to visited set.
  337. visited_set.set({ url, module_type });
  338. }
  339. }
  340. // FIXME: 6. Let options be the descendant script fetch options for module script's fetch options.
  341. // FIXME: 7. Assert: options is not null, as module script is a JavaScript module script.
  342. // 8. Let pendingCount be the length of moduleRequests.
  343. auto pending_count = module_requests.size();
  344. // 9. If pendingCount is zero, run onComplete with module script.
  345. if (pending_count == 0) {
  346. on_complete(&module_script);
  347. return;
  348. }
  349. // 10. Let failed be false.
  350. auto context = DescendantFetchingContext::create();
  351. context->set_pending_count(pending_count);
  352. context->set_failed(false);
  353. context->set_on_complete(move(on_complete));
  354. // 11. For each moduleRequest in moduleRequests, perform the internal module script graph fetching procedure given moduleRequest,
  355. // fetch client settings object, destination, options, module script, visited set, and onInternalFetchingComplete as defined below.
  356. // If performFetch was given, pass it along as well.
  357. for (auto const& module_request : module_requests) {
  358. // FIXME: Pass options and performFetch if given.
  359. fetch_internal_module_script_graph(module_request, fetch_client_settings_object, destination, module_script, visited_set, [context, &module_script](auto result) mutable {
  360. // onInternalFetchingComplete given result is the following algorithm:
  361. // 1. If failed is true, then abort these steps.
  362. if (context->failed())
  363. return;
  364. // 2. If result is null, then set failed to true, run onComplete with null, and abort these steps.
  365. if (!result) {
  366. context->set_failed(true);
  367. context->on_complete(nullptr);
  368. return;
  369. }
  370. // 3. Assert: pendingCount is greater than zero.
  371. VERIFY(context->pending_count() > 0);
  372. // 4. Decrement pendingCount by one.
  373. context->decrement_pending_count();
  374. // 5. If pendingCount is zero, run onComplete with module script.
  375. if (context->pending_count() == 0)
  376. context->on_complete(&module_script);
  377. });
  378. }
  379. }
  380. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
  381. void fetch_single_module_script(AK::URL const& url, EnvironmentSettingsObject&, StringView, EnvironmentSettingsObject& module_map_settings_object, AK::URL const&, Optional<JS::ModuleRequest> const& module_request, TopLevelModule, OnFetchScriptComplete on_complete)
  382. {
  383. // 1. Let moduleType be "javascript".
  384. DeprecatedString module_type = "javascript"sv;
  385. // 2. If moduleRequest was given, then set moduleType to the result of running the module type from module request steps given moduleRequest.
  386. if (module_request.has_value())
  387. module_type = module_type_from_module_request(*module_request);
  388. // 3. Assert: the result of running the module type allowed steps given moduleType and module map settings object is true.
  389. // Otherwise we would not have reached this point because a failure would have been raised when inspecting moduleRequest.[[Assertions]]
  390. // in create a JavaScript module script or fetch an import() module script graph.
  391. VERIFY(module_map_settings_object.module_type_allowed(module_type));
  392. // 4. Let moduleMap be module map settings object's module map.
  393. auto& module_map = module_map_settings_object.module_map();
  394. // 5. If moduleMap[(url, moduleType)] is "fetching", wait in parallel until that entry's value changes,
  395. // then queue a task on the networking task source to proceed with running the following steps.
  396. if (module_map.is_fetching(url, module_type)) {
  397. module_map.wait_for_change(url, module_type, [on_complete = move(on_complete)](auto entry) {
  398. // FIXME: This should queue a task.
  399. // FIXME: This should run other steps, for now we just assume the script loaded.
  400. VERIFY(entry.type == ModuleMap::EntryType::ModuleScript);
  401. on_complete(entry.module_script);
  402. });
  403. return;
  404. }
  405. // 6. If moduleMap[(url, moduleType)] exists, run onComplete given moduleMap[(url, moduleType)], and return.
  406. auto entry = module_map.get(url, module_type);
  407. if (entry.has_value() && entry->type == ModuleMap::EntryType::ModuleScript) {
  408. on_complete(entry->module_script);
  409. return;
  410. }
  411. // 7. Set moduleMap[(url, moduleType)] to "fetching".
  412. module_map.set(url, module_type, { ModuleMap::EntryType::Fetching, nullptr });
  413. // FIXME: Implement non ad-hoc version of steps 8 to 20.
  414. auto request = LoadRequest::create_for_url_on_page(url, nullptr);
  415. ResourceLoader::the().load(
  416. request,
  417. [url, module_type, &module_map_settings_object, on_complete = move(on_complete), &module_map](StringView data, auto& response_headers, auto) {
  418. if (data.is_null()) {
  419. dbgln("Failed to load module {}", url);
  420. module_map.set(url, module_type, { ModuleMap::EntryType::Failed, nullptr });
  421. on_complete(nullptr);
  422. return;
  423. }
  424. auto content_type_header = response_headers.get("Content-Type");
  425. if (!content_type_header.has_value()) {
  426. dbgln("Module has no content type! {}", url);
  427. module_map.set(url, module_type, { ModuleMap::EntryType::Failed, nullptr });
  428. on_complete(nullptr);
  429. return;
  430. }
  431. if (MimeSniff::is_javascript_mime_type_essence_match(*content_type_header) && module_type == "javascript"sv) {
  432. auto module_script = JavaScriptModuleScript::create(url.basename(), data, module_map_settings_object, url).release_value_but_fixme_should_propagate_errors();
  433. module_map.set(url, module_type, { ModuleMap::EntryType::ModuleScript, module_script });
  434. on_complete(module_script);
  435. return;
  436. }
  437. dbgln("Module has no JS content type! {} of type {}, with content {}", url, module_type, *content_type_header);
  438. module_map.set(url, module_type, { ModuleMap::EntryType::Failed, nullptr });
  439. on_complete(nullptr);
  440. },
  441. [module_type, url](auto&, auto) {
  442. dbgln("Failed to load module script");
  443. TODO();
  444. });
  445. }
  446. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-script-tree
  447. void fetch_external_module_script_graph(AK::URL const& url, EnvironmentSettingsObject& settings_object, OnFetchScriptComplete on_complete)
  448. {
  449. // 1. Disallow further import maps given settings object.
  450. settings_object.disallow_further_import_maps();
  451. // 2. Fetch a single module script given url, settings object, "script", options, settings object, "client", true, and with the following steps given result:
  452. // FIXME: Pass options.
  453. fetch_single_module_script(url, settings_object, "script"sv, settings_object, "client"sv, {}, TopLevelModule::Yes, [&settings_object, on_complete = move(on_complete), url](auto result) mutable {
  454. // 1. If result is null, run onComplete given null, and abort these steps.
  455. if (!result) {
  456. on_complete(nullptr);
  457. return;
  458. }
  459. // 2. Let visited set be « (url, "javascript") ».
  460. HashTable<ModuleLocationTuple> visited_set;
  461. visited_set.set({ url, "javascript"sv });
  462. // 3. Fetch the descendants of and link result given settings object, "script", visited set, and onComplete.
  463. auto& module_script = verify_cast<JavaScriptModuleScript>(*result);
  464. fetch_descendants_of_and_link_a_module_script(module_script, settings_object, "script"sv, move(visited_set), move(on_complete));
  465. });
  466. }
  467. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-an-inline-module-script-graph
  468. void fetch_inline_module_script_graph(DeprecatedString const& filename, DeprecatedString const& source_text, AK::URL const& base_url, EnvironmentSettingsObject& settings_object, OnFetchScriptComplete on_complete)
  469. {
  470. // 1. Disallow further import maps given settings object.
  471. settings_object.disallow_further_import_maps();
  472. // 2. Let script be the result of creating a JavaScript module script using source text, settings object, base URL, and options.
  473. auto script = JavaScriptModuleScript::create(filename, source_text.view(), settings_object, base_url).release_value_but_fixme_should_propagate_errors();
  474. // 3. If script is null, run onComplete given null, and return.
  475. if (!script) {
  476. on_complete(nullptr);
  477. return;
  478. }
  479. // 4. Let visited set be an empty set.
  480. HashTable<ModuleLocationTuple> visited_set;
  481. // 5. Fetch the descendants of and link script, given settings object, the destination "script", visited set, and onComplete.
  482. fetch_descendants_of_and_link_a_module_script(*script, settings_object, "script"sv, visited_set, move(on_complete));
  483. }
  484. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-the-descendants-of-and-link-a-module-script
  485. void fetch_descendants_of_and_link_a_module_script(JavaScriptModuleScript& module_script, EnvironmentSettingsObject& fetch_client_settings_object, StringView destination, HashTable<ModuleLocationTuple> const& visited_set, OnFetchScriptComplete on_complete)
  486. {
  487. // 1. Fetch the descendants of module script, given fetch client settings object, destination, visited set, and onFetchDescendantsComplete as defined below.
  488. // If performFetch was given, pass it along as well.
  489. // FIXME: Pass performFetch if given.
  490. fetch_descendants_of_a_module_script(module_script, fetch_client_settings_object, destination, visited_set, [&fetch_client_settings_object, on_complete = move(on_complete)](auto result) {
  491. // onFetchDescendantsComplete given result is the following algorithm:
  492. // 1. If result is null, then run onComplete given result, and abort these steps.
  493. if (!result) {
  494. on_complete(nullptr);
  495. return;
  496. }
  497. // FIXME: This is an ad-hoc hack to make sure that there's an execution context on the VM stack in case linking throws an exception.
  498. auto& vm = fetch_client_settings_object.vm();
  499. vm.push_execution_context(fetch_client_settings_object.realm_execution_context());
  500. // FIXME: 2. Let parse error be the result of finding the first parse error given result.
  501. // 3. If parse error is null, then:
  502. if (auto& module_script = verify_cast<JavaScriptModuleScript>(*result); module_script.record()) {
  503. // 1. Let record be result's record.
  504. auto const& record = *module_script.record();
  505. // 2. Perform record.Link().
  506. auto linking_result = const_cast<JS::SourceTextModule&>(record).link(result->vm());
  507. // If this throws an exception, set result's error to rethrow to that exception.
  508. if (linking_result.is_throw_completion()) {
  509. result->set_error_to_rethrow(linking_result.release_error().value().value());
  510. }
  511. } else {
  512. // FIXME: 4. Otherwise, set result's error to rethrow to parse error.
  513. TODO();
  514. }
  515. // FIXME: This undoes the ad-hoc hack above.
  516. vm.pop_execution_context();
  517. // 5. Run onComplete given result.
  518. on_complete(result);
  519. });
  520. }
  521. }