Fetching.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. /*
  2. * Copyright (c) 2022-2023, networkException <networkexception@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Heap/HeapFunction.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/Scripting/TemporaryExecutionContext.h>
  22. #include <LibWeb/HTML/Window.h>
  23. #include <LibWeb/Infra/Strings.h>
  24. #include <LibWeb/MimeSniff/MimeType.h>
  25. #include <LibWeb/URL/URL.h>
  26. namespace Web::HTML {
  27. OnFetchScriptComplete create_on_fetch_script_complete(JS::Heap& heap, Function<void(JS::GCPtr<Script>)> function)
  28. {
  29. return JS::create_heap_function(heap, move(function));
  30. }
  31. ScriptFetchOptions default_classic_script_fetch_options()
  32. {
  33. // The default classic script fetch options are a script fetch options whose cryptographic nonce is the empty string,
  34. // integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is "same-origin",
  35. // referrer policy is the empty string, and fetch priority is "auto".
  36. return ScriptFetchOptions {
  37. .cryptographic_nonce = {},
  38. .integrity_metadata = {},
  39. .parser_metadata = Fetch::Infrastructure::Request::ParserMetadata::NotParserInserted,
  40. .credentials_mode = Fetch::Infrastructure::Request::CredentialsMode::SameOrigin,
  41. .referrer_policy = {},
  42. .fetch_priority = Fetch::Infrastructure::Request::Priority::Auto
  43. };
  44. }
  45. // https://html.spec.whatwg.org/multipage/webappapis.html#module-type-from-module-request
  46. DeprecatedString module_type_from_module_request(JS::ModuleRequest const& module_request)
  47. {
  48. // 1. Let moduleType be "javascript".
  49. DeprecatedString module_type = "javascript"sv;
  50. // 2. If moduleRequest.[[Assertions]] has a Record entry such that entry.[[Key]] is "type", then:
  51. for (auto const& entry : module_request.assertions) {
  52. if (entry.key != "type"sv)
  53. continue;
  54. // 1. If entry.[[Value]] is "javascript", then set moduleType to null.
  55. if (entry.value == "javascript"sv)
  56. module_type = nullptr;
  57. // 2. Otherwise, set moduleType to entry.[[Value]].
  58. else
  59. module_type = entry.value;
  60. }
  61. // 3. Return moduleType.
  62. return module_type;
  63. }
  64. // https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier
  65. WebIDL::ExceptionOr<AK::URL> resolve_module_specifier(Optional<Script&> referring_script, DeprecatedString const& specifier)
  66. {
  67. // 1. Let settingsObject and baseURL be null.
  68. Optional<EnvironmentSettingsObject&> settings_object;
  69. Optional<AK::URL const&> base_url;
  70. // 2. If referringScript is not null, then:
  71. if (referring_script.has_value()) {
  72. // 1. Set settingsObject to referringScript's settings object.
  73. settings_object = referring_script->settings_object();
  74. // 2. Set baseURL to referringScript's base URL.
  75. base_url = referring_script->base_url();
  76. }
  77. // 3. Otherwise:
  78. else {
  79. // 1. Assert: there is a current settings object.
  80. // NOTE: This is handled by the current_settings_object() accessor.
  81. // 2. Set settingsObject to the current settings object.
  82. settings_object = current_settings_object();
  83. // 3. Set baseURL to settingsObject's API base URL.
  84. base_url = settings_object->api_base_url();
  85. }
  86. // 4. Let importMap be an empty import map.
  87. ImportMap import_map;
  88. // 5. If settingsObject's global object implements Window, then set importMap to settingsObject's global object's import map.
  89. if (is<Window>(settings_object->global_object()))
  90. import_map = verify_cast<Window>(settings_object->global_object()).import_map();
  91. // 6. Let baseURLString be baseURL, serialized.
  92. auto base_url_string = base_url->serialize();
  93. // 7. Let asURL be the result of resolving a URL-like module specifier given specifier and baseURL.
  94. auto as_url = resolve_url_like_module_specifier(specifier, *base_url);
  95. // 8. Let normalizedSpecifier be the serialization of asURL, if asURL is non-null; otherwise, specifier.
  96. auto normalized_specifier = as_url.has_value() ? as_url->serialize() : specifier;
  97. // 9. For each scopePrefix → scopeImports of importMap's scopes:
  98. for (auto const& entry : import_map.scopes()) {
  99. // FIXME: Clarify if the serialization steps need to be run here. The steps below assume
  100. // scopePrefix to be a string.
  101. auto const& scope_prefix = entry.key.serialize();
  102. auto const& scope_imports = entry.value;
  103. // 1. If scopePrefix is baseURLString, or if scopePrefix ends with U+002F (/) and scopePrefix is a code unit prefix of baseURLString, then:
  104. if (scope_prefix == base_url_string || (scope_prefix.ends_with("/"sv) && Infra::is_code_unit_prefix(scope_prefix, base_url_string))) {
  105. // 1. Let scopeImportsMatch be the result of resolving an imports match given normalizedSpecifier, asURL, and scopeImports.
  106. auto scope_imports_match = TRY(resolve_imports_match(normalized_specifier, as_url, scope_imports));
  107. // 2. If scopeImportsMatch is not null, then return scopeImportsMatch.
  108. if (scope_imports_match.has_value())
  109. return scope_imports_match.release_value();
  110. }
  111. }
  112. // 10. Let topLevelImportsMatch be the result of resolving an imports match given normalizedSpecifier, asURL, and importMap's imports.
  113. auto top_level_imports_match = TRY(resolve_imports_match(normalized_specifier, as_url, import_map.imports()));
  114. // 11. If topLevelImportsMatch is not null, then return topLevelImportsMatch.
  115. if (top_level_imports_match.has_value())
  116. return top_level_imports_match.release_value();
  117. // 12. If asURL is not null, then return asURL.
  118. if (as_url.has_value())
  119. return as_url.release_value();
  120. // 13. Throw a TypeError indicating that specifier was a bare specifier, but was not remapped to anything by importMap.
  121. 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() };
  122. }
  123. // https://html.spec.whatwg.org/multipage/webappapis.html#resolving-an-imports-match
  124. WebIDL::ExceptionOr<Optional<AK::URL>> resolve_imports_match(DeprecatedString const& normalized_specifier, Optional<AK::URL> as_url, ModuleSpecifierMap const& specifier_map)
  125. {
  126. // 1. For each specifierKey → resolutionResult of specifierMap:
  127. for (auto const& [specifier_key, resolution_result] : specifier_map) {
  128. // 1. If specifierKey is normalizedSpecifier, then:
  129. if (specifier_key == normalized_specifier) {
  130. // 1. If resolutionResult is null, then throw a TypeError indicating that 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. Return resolutionResult.
  136. return resolution_result;
  137. }
  138. // 2. If all of the following are true:
  139. if (
  140. // - specifierKey ends with U+002F (/);
  141. specifier_key.ends_with("/"sv) &&
  142. // - specifierKey is a code unit prefix of normalizedSpecifier; and
  143. Infra::is_code_unit_prefix(specifier_key, normalized_specifier) &&
  144. // - either asURL is null, or asURL is special,
  145. (!as_url.has_value() || as_url->is_special())
  146. // then:
  147. ) {
  148. // 1. If resolutionResult is null, then throw a TypeError indicating that the resolution of specifierKey was blocked by a null entry.
  149. if (!resolution_result.has_value())
  150. 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() };
  151. // 2. Assert: resolutionResult is a URL.
  152. VERIFY(resolution_result->is_valid());
  153. // 3. Let afterPrefix be the portion of normalizedSpecifier after the initial specifierKey prefix.
  154. // FIXME: Clarify if this is meant by the portion after the initial specifierKey prefix.
  155. auto after_prefix = normalized_specifier.substring(specifier_key.length());
  156. // 4. Assert: resolutionResult, serialized, ends with U+002F (/), as enforced during parsing.
  157. VERIFY(resolution_result->serialize().ends_with("/"sv));
  158. // 5. Let url be the result of URL parsing afterPrefix with resolutionResult.
  159. auto url = URL::parse(after_prefix, *resolution_result);
  160. // 6. If url is failure, then throw a TypeError indicating that resolution of normalizedSpecifier was blocked since the afterPrefix portion
  161. // could not be URL-parsed relative to the resolutionResult mapped to by the specifierKey prefix.
  162. if (!url.is_valid())
  163. 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() };
  164. // 7. Assert: url is a URL.
  165. VERIFY(url.is_valid());
  166. // 8. If the serialization of resolutionResult is not a code unit prefix of the serialization of url, then throw a TypeError indicating
  167. // that the resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.
  168. if (!Infra::is_code_unit_prefix(resolution_result->serialize(), url.serialize()))
  169. 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() };
  170. // 9. Return url.
  171. return url;
  172. }
  173. }
  174. // 2. Return null.
  175. return Optional<AK::URL> {};
  176. }
  177. // https://html.spec.whatwg.org/multipage/webappapis.html#resolving-a-url-like-module-specifier
  178. Optional<AK::URL> resolve_url_like_module_specifier(DeprecatedString const& specifier, AK::URL const& base_url)
  179. {
  180. // 1. If specifier starts with "/", "./", or "../", then:
  181. if (specifier.starts_with("/"sv) || specifier.starts_with("./"sv) || specifier.starts_with("../"sv)) {
  182. // 1. Let url be the result of URL parsing specifier with baseURL.
  183. auto url = URL::parse(specifier, base_url);
  184. // 2. If url is failure, then return null.
  185. if (!url.is_valid())
  186. return {};
  187. // 3. Return url.
  188. return url;
  189. }
  190. // 2. Let url be the result of URL parsing specifier (with no base URL).
  191. auto url = URL::parse(specifier);
  192. // 3. If url is failure, then return null.
  193. if (!url.is_valid())
  194. return {};
  195. // 4. Return url.
  196. return url;
  197. }
  198. // https://html.spec.whatwg.org/multipage/webappapis.html#set-up-the-classic-script-request
  199. static void set_up_classic_script_request(Fetch::Infrastructure::Request& request, ScriptFetchOptions const& options)
  200. {
  201. // Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's
  202. // integrity metadata, its parser metadata to options's parser metadata, its referrer policy to options's referrer
  203. // policy, its render-blocking to options's render-blocking, and its priority to options's fetch priority.
  204. request.set_cryptographic_nonce_metadata(options.cryptographic_nonce);
  205. request.set_integrity_metadata(options.integrity_metadata);
  206. request.set_parser_metadata(options.parser_metadata);
  207. request.set_referrer_policy(options.referrer_policy);
  208. request.set_render_blocking(options.render_blocking);
  209. request.set_priority(options.fetch_priority);
  210. }
  211. // https://html.spec.whatwg.org/multipage/webappapis.html#set-up-the-module-script-request
  212. static void set_up_module_script_request(Fetch::Infrastructure::Request& request, ScriptFetchOptions const& options)
  213. {
  214. // Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's
  215. // integrity metadata, its parser metadata to options's parser metadata, its credentials mode to options's credentials
  216. // mode, its referrer policy to options's referrer policy, its render-blocking to options's render-blocking, and its
  217. // priority to options's fetch priority.
  218. request.set_cryptographic_nonce_metadata(options.cryptographic_nonce);
  219. request.set_integrity_metadata(options.integrity_metadata);
  220. request.set_parser_metadata(options.parser_metadata);
  221. request.set_credentials_mode(options.credentials_mode);
  222. request.set_referrer_policy(options.referrer_policy);
  223. request.set_render_blocking(options.render_blocking);
  224. request.set_priority(options.fetch_priority);
  225. }
  226. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-classic-script
  227. 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)
  228. {
  229. auto& realm = element->realm();
  230. auto& vm = realm.vm();
  231. // 1. Let request be the result of creating a potential-CORS request given url, "script", and CORS setting.
  232. auto request = create_potential_CORS_request(vm, url, Fetch::Infrastructure::Request::Destination::Script, cors_setting);
  233. // 2. Set request's client to settings object.
  234. request->set_client(&settings_object);
  235. // 3. Set request's initiator type to "script".
  236. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Script);
  237. // 4. Set up the classic script request given request and options.
  238. set_up_classic_script_request(*request, options);
  239. // 5. Fetch request with the following processResponseConsumeBody steps given response response and null, failure,
  240. // or a byte sequence bodyBytes:
  241. Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  242. 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) {
  243. // 1. Set response to response's unsafe response.
  244. response = response->unsafe_response();
  245. // 2. If either of the following conditions are met:
  246. // - bodyBytes is null or failure; or
  247. // - response's status is not an ok status,
  248. if (body_bytes.template has<Empty>() || body_bytes.template has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>() || !Fetch::Infrastructure::is_ok_status(response->status())) {
  249. // then run onComplete given null, and abort these steps.
  250. on_complete->function()(nullptr);
  251. return;
  252. }
  253. // 3. Let potentialMIMETypeForEncoding be the result of extracting a MIME type given response's header list.
  254. auto potential_mime_type_for_encoding = response->header_list()->extract_mime_type().release_value_but_fixme_should_propagate_errors();
  255. // 4. Set character encoding to the result of legacy extracting an encoding given potentialMIMETypeForEncoding
  256. // and character encoding.
  257. auto extracted_character_encoding = Fetch::Infrastructure::legacy_extract_an_encoding(potential_mime_type_for_encoding, character_encoding);
  258. // 5. Let source text be the result of decoding bodyBytes to Unicode, using character encoding as the fallback
  259. // encoding.
  260. auto fallback_decoder = TextCodec::decoder_for(extracted_character_encoding);
  261. VERIFY(fallback_decoder.has_value());
  262. 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();
  263. // 6. Let muted errors be true if response was CORS-cross-origin, and false otherwise.
  264. auto muted_errors = response->is_cors_cross_origin() ? ClassicScript::MutedErrors::Yes : ClassicScript::MutedErrors::No;
  265. // 7. Let script be the result of creating a classic script given source text, settings object, response's URL,
  266. // options, and muted errors.
  267. // FIXME: Pass options.
  268. auto response_url = response->url().value_or({});
  269. auto script = ClassicScript::create(response_url.to_deprecated_string(), source_text, settings_object, response_url, 1, muted_errors);
  270. // 8. Run onComplete given script.
  271. on_complete->function()(script);
  272. };
  273. TRY(Fetch::Fetching::fetch(element->realm(), request, Fetch::Infrastructure::FetchAlgorithms::create(vm, move(fetch_algorithms_input))));
  274. return {};
  275. }
  276. // https://html.spec.whatwg.org/multipage/webappapis.html#internal-module-script-graph-fetching-procedure
  277. 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, OnFetchScriptComplete on_complete)
  278. {
  279. // 1. Let url be the result of resolving a module specifier given referringScript and moduleRequest.[[Specifier]].
  280. auto url = MUST(resolve_module_specifier(referring_script, module_request.module_specifier));
  281. // 2. Assert: the previous step never throws an exception, because resolving a module specifier must have been previously successful with these same two arguments.
  282. // NOTE: Handled by MUST above.
  283. // 3. Let moduleType be the result of running the module type from module request steps given moduleRequest.
  284. auto module_type = module_type_from_module_request(module_request);
  285. // 4. Assert: visited set contains (url, moduleType).
  286. VERIFY(visited_set.contains({ url, module_type }));
  287. // onSingleFetchComplete given result is the following algorithm:
  288. auto on_single_fetch_complete = create_on_fetch_script_complete(realm.heap(), [&realm, on_complete, &fetch_client_settings_object, destination, visited_set](auto result) mutable {
  289. // 1. If result is null, run onComplete with null, and abort these steps.
  290. if (!result) {
  291. on_complete->function()(nullptr);
  292. return;
  293. }
  294. // 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.
  295. // FIXME: Pass performFetch if given.
  296. auto& module_script = verify_cast<JavaScriptModuleScript>(*result);
  297. fetch_descendants_of_a_module_script(realm, module_script, fetch_client_settings_object, destination, visited_set, on_complete);
  298. });
  299. // 5. Fetch a single module script given url, fetch client settings object, destination, options, referringScript's settings object,
  300. // referringScript's base URL, moduleRequest, false, and onSingleFetchComplete as defined below. If performFetch was given, pass it along as well.
  301. // FIXME: Pass performFetch if given.
  302. fetch_single_module_script(realm, url, fetch_client_settings_object, destination, options, referring_script.settings_object(), referring_script.base_url(), module_request, TopLevelModule::No, on_single_fetch_complete);
  303. }
  304. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-the-descendants-of-a-module-script
  305. 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, OnFetchScriptComplete on_complete)
  306. {
  307. // 1. If module script's record is null, run onComplete with module script and return.
  308. if (!module_script.record()) {
  309. on_complete->function()(&module_script);
  310. return;
  311. }
  312. // 2. Let record be module script's record.
  313. auto const& record = module_script.record();
  314. // 3. If record is not a Cyclic Module Record, or if record.[[RequestedModules]] is empty, run onComplete with module script and return.
  315. // FIXME: Currently record is always a cyclic module.
  316. if (record->requested_modules().is_empty()) {
  317. on_complete->function()(&module_script);
  318. return;
  319. }
  320. // 4. Let moduleRequests be a new empty list.
  321. Vector<JS::ModuleRequest> module_requests;
  322. // 5. For each ModuleRequest Record requested of record.[[RequestedModules]],
  323. for (auto const& requested : record->requested_modules()) {
  324. // 1. Let url be the result of resolving a module specifier given module script and requested.[[Specifier]].
  325. auto url = MUST(resolve_module_specifier(module_script, requested.module_specifier));
  326. // 2. Assert: the previous step never throws an exception, because resolving a module specifier must have been previously successful with these same two arguments.
  327. // NOTE: Handled by MUST above.
  328. // 3. Let moduleType be the result of running the module type from module request steps given requested.
  329. auto module_type = module_type_from_module_request(requested);
  330. // 4. If visited set does not contain (url, moduleType), then:
  331. if (!visited_set.contains({ url, module_type })) {
  332. // 1. Append requested to moduleRequests.
  333. module_requests.append(requested);
  334. // 2. Append (url, moduleType) to visited set.
  335. visited_set.set({ url, module_type });
  336. }
  337. }
  338. // FIXME: 6. Let options be the descendant script fetch options for module script's fetch options.
  339. ScriptFetchOptions options;
  340. // FIXME: 7. Assert: options is not null, as module script is a JavaScript module script.
  341. // 8. Let pendingCount be the length of moduleRequests.
  342. auto pending_count = module_requests.size();
  343. // 9. If pendingCount is zero, run onComplete with module script.
  344. if (pending_count == 0) {
  345. on_complete->function()(&module_script);
  346. return;
  347. }
  348. // 10. Let failed be false.
  349. bool failed = false;
  350. // 11. For each moduleRequest in moduleRequests, perform the internal module script graph fetching procedure given moduleRequest,
  351. // fetch client settings object, destination, options, module script, visited set, and onInternalFetchingComplete as defined below.
  352. // If performFetch was given, pass it along as well.
  353. for (auto const& module_request : module_requests) {
  354. // onInternalFetchingComplete given result is the following algorithm:
  355. auto on_internal_fetching_complete = create_on_fetch_script_complete(realm.heap(), [failed, pending_count, &module_script, on_complete](auto result) mutable {
  356. // 1. If failed is true, then abort these steps.
  357. if (failed)
  358. return;
  359. // 2. If result is null, then set failed to true, run onComplete with null, and abort these steps.
  360. if (!result) {
  361. failed = true;
  362. on_complete->function()(nullptr);
  363. return;
  364. }
  365. // 3. Assert: pendingCount is greater than zero.
  366. VERIFY(pending_count > 0);
  367. // 4. Decrement pendingCount by one.
  368. --pending_count;
  369. // 5. If pendingCount is zero, run onComplete with module script.
  370. if (pending_count == 0)
  371. on_complete->function()(&module_script);
  372. });
  373. // FIXME: Pass performFetch if given.
  374. fetch_internal_module_script_graph(realm, module_request, fetch_client_settings_object, destination, options, module_script, visited_set, on_internal_fetching_complete);
  375. }
  376. }
  377. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
  378. void fetch_single_module_script(JS::Realm& realm,
  379. AK::URL const& url,
  380. EnvironmentSettingsObject& fetch_client,
  381. Fetch::Infrastructure::Request::Destination destination,
  382. ScriptFetchOptions const& options,
  383. EnvironmentSettingsObject& settings_object,
  384. Web::Fetch::Infrastructure::Request::ReferrerType const& referrer,
  385. Optional<JS::ModuleRequest> const& module_request,
  386. TopLevelModule is_top_level,
  387. OnFetchScriptComplete on_complete)
  388. {
  389. // 1. Let moduleType be "javascript".
  390. DeprecatedString module_type = "javascript"sv;
  391. // 2. If moduleRequest was given, then set moduleType to the result of running the module type from module request steps given moduleRequest.
  392. if (module_request.has_value())
  393. module_type = module_type_from_module_request(*module_request);
  394. // 3. Assert: the result of running the module type allowed steps given moduleType and settingsObject is true.
  395. // Otherwise we would not have reached this point because a failure would have been raised when inspecting moduleRequest.[[Assertions]]
  396. // in create a JavaScript module script or fetch a single imported module script.
  397. VERIFY(settings_object.module_type_allowed(module_type));
  398. // 4. Let moduleMap be settingsObject's module map.
  399. auto& module_map = settings_object.module_map();
  400. // 5. If moduleMap[(url, moduleType)] is "fetching", wait in parallel until that entry's value changes,
  401. // then queue a task on the networking task source to proceed with running the following steps.
  402. if (module_map.is_fetching(url, module_type)) {
  403. module_map.wait_for_change(realm.heap(), url, module_type, [on_complete](auto entry) -> void {
  404. // FIXME: This should queue a task.
  405. // FIXME: This should run other steps, for now we just assume the script loaded.
  406. VERIFY(entry.type == ModuleMap::EntryType::ModuleScript);
  407. on_complete->function()(entry.module_script);
  408. });
  409. return;
  410. }
  411. // 6. If moduleMap[(url, moduleType)] exists, run onComplete given moduleMap[(url, moduleType)], and return.
  412. auto entry = module_map.get(url, module_type);
  413. if (entry.has_value() && entry->type == ModuleMap::EntryType::ModuleScript) {
  414. on_complete->function()(entry->module_script);
  415. return;
  416. }
  417. // 7. Set moduleMap[(url, moduleType)] to "fetching".
  418. module_map.set(url, module_type, { ModuleMap::EntryType::Fetching, nullptr });
  419. // 8. Let request be a new request whose URL is url, destination is destination, mode is "cors", referrer is referrer, and client is fetchClient.
  420. auto request = Fetch::Infrastructure::Request::create(realm.vm());
  421. request->set_url(url);
  422. request->set_destination(destination);
  423. request->set_mode(Fetch::Infrastructure::Request::Mode::CORS);
  424. request->set_referrer(referrer);
  425. request->set_client(&fetch_client);
  426. // 9. If destination is "worker", "sharedworker", or "serviceworker", and isTopLevel is true, then set request's mode to "same-origin".
  427. if ((destination == Fetch::Infrastructure::Request::Destination::Worker || destination == Fetch::Infrastructure::Request::Destination::SharedWorker || destination == Fetch::Infrastructure::Request::Destination::ServiceWorker) && is_top_level == TopLevelModule::Yes)
  428. request->set_mode(Fetch::Infrastructure::Request::Mode::SameOrigin);
  429. // 10. Set request's initiator type to "script".
  430. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Script);
  431. // 11. Set up the module script request given request and options.
  432. set_up_module_script_request(request, options);
  433. // 12. If performFetch was given, run performFetch with request, isTopLevel, and with processResponseConsumeBody as defined below.
  434. // Otherwise, fetch request with processResponseConsumeBody set to processResponseConsumeBody as defined below.
  435. // In both cases, let processResponseConsumeBody given response response and null, failure, or a byte sequence bodyBytes be the following algorithm:
  436. // FIXME: Run performFetch if given.
  437. Web::Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  438. fetch_algorithms_input.process_response_consume_body = [&module_map, url, module_type, &settings_object, on_complete](JS::NonnullGCPtr<Fetch::Infrastructure::Response> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {
  439. // 1. If either of the following conditions are met:
  440. // - bodyBytes is null or failure; or
  441. // - response's status is not an ok status,
  442. if (body_bytes.has<Empty>() || body_bytes.has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>() || !Fetch::Infrastructure::is_ok_status(response->status())) {
  443. // then set moduleMap[(url, moduleType)] to null, run onComplete given null, and abort these steps.
  444. module_map.set(url, module_type, { ModuleMap::EntryType::Failed, nullptr });
  445. on_complete->function()(nullptr);
  446. return;
  447. }
  448. // 2. Let sourceText be the result of UTF-8 decoding bodyBytes.
  449. auto decoder = TextCodec::decoder_for("UTF-8"sv);
  450. VERIFY(decoder.has_value());
  451. 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();
  452. // 3. Let mimeType be the result of extracting a MIME type from response's header list.
  453. auto mime_type = response->header_list()->extract_mime_type().release_value_but_fixme_should_propagate_errors();
  454. // 4. Let moduleScript be null.
  455. JS::GCPtr<JavaScriptModuleScript> module_script;
  456. // FIXME: 5. Let referrerPolicy be the result of parsing the `Referrer-Policy` header given response. [REFERRERPOLICY]
  457. // FIXME: 6. If referrerPolicy is not the empty string, set options's referrer policy to referrerPolicy.
  458. // 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, settingsObject, response's URL, and options.
  459. // FIXME: Pass options.
  460. if (mime_type->is_javascript() && module_type == "javascript")
  461. module_script = JavaScriptModuleScript::create(url.basename(), source_text, settings_object, response->url().value_or({})).release_value_but_fixme_should_propagate_errors();
  462. // 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.
  463. // 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.
  464. // 10. Set moduleMap[(url, moduleType)] to moduleScript, and run onComplete given moduleScript.
  465. module_map.set(url, module_type, { ModuleMap::EntryType::ModuleScript, module_script });
  466. on_complete->function()(module_script);
  467. };
  468. Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(realm.vm(), move(fetch_algorithms_input))).release_value_but_fixme_should_propagate_errors();
  469. }
  470. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-module-script-tree
  471. void fetch_external_module_script_graph(JS::Realm& realm, AK::URL const& url, EnvironmentSettingsObject& settings_object, ScriptFetchOptions const& options, OnFetchScriptComplete on_complete)
  472. {
  473. // 1. Disallow further import maps given settingsObject.
  474. settings_object.disallow_further_import_maps();
  475. auto steps = create_on_fetch_script_complete(realm.heap(), [&realm, &settings_object, on_complete, url](auto result) mutable {
  476. // 1. If result is null, run onComplete given null, and abort these steps.
  477. if (!result) {
  478. on_complete->function()(nullptr);
  479. return;
  480. }
  481. // 2. Fetch the descendants of and link result given settingsObject, "script", and onComplete.
  482. auto& module_script = verify_cast<JavaScriptModuleScript>(*result);
  483. fetch_descendants_of_and_link_a_module_script(realm, module_script, settings_object, Fetch::Infrastructure::Request::Destination::Script, on_complete);
  484. });
  485. // 2. Fetch a single module script given url, settingsObject, "script", options, settingsObject, "client", true, and with the following steps given result:
  486. fetch_single_module_script(realm, url, settings_object, Fetch::Infrastructure::Request::Destination::Script, options, settings_object, Web::Fetch::Infrastructure::Request::Referrer::Client, {}, TopLevelModule::Yes, steps);
  487. }
  488. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-an-inline-module-script-graph
  489. void fetch_inline_module_script_graph(JS::Realm& realm, DeprecatedString const& filename, DeprecatedString const& source_text, AK::URL const& base_url, EnvironmentSettingsObject& settings_object, OnFetchScriptComplete on_complete)
  490. {
  491. // 1. Disallow further import maps given settingsObject.
  492. settings_object.disallow_further_import_maps();
  493. // 2. Let script be the result of creating a JavaScript module script using sourceText, settingsObject, baseURL, and options.
  494. auto script = JavaScriptModuleScript::create(filename, source_text.view(), settings_object, base_url).release_value_but_fixme_should_propagate_errors();
  495. // 3. If script is null, run onComplete given null, and return.
  496. if (!script) {
  497. on_complete->function()(nullptr);
  498. return;
  499. }
  500. // 5. Fetch the descendants of and link script, given settingsObject, "script", and onComplete.
  501. fetch_descendants_of_and_link_a_module_script(realm, *script, settings_object, Fetch::Infrastructure::Request::Destination::Script, on_complete);
  502. }
  503. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-imported-module-script
  504. void fetch_single_imported_module_script(JS::Realm& realm,
  505. AK::URL const& url,
  506. EnvironmentSettingsObject& fetch_client,
  507. Fetch::Infrastructure::Request::Destination destination,
  508. ScriptFetchOptions const& options,
  509. EnvironmentSettingsObject& settings_object,
  510. Fetch::Infrastructure::Request::Referrer referrer,
  511. JS::ModuleRequest const& module_request,
  512. OnFetchScriptComplete on_complete)
  513. {
  514. // 1. Assert: moduleRequest.[[Attributes]] does not contain any Record entry such that entry.[[Key]] is not "type",
  515. // because we only asked for "type" attributes in HostGetSupportedImportAttributes.
  516. for (auto const& entry : module_request.assertions)
  517. VERIFY(entry.key == "type"sv);
  518. // 2. Let moduleType be the result of running the module type from module request steps given moduleRequest.
  519. auto module_type = module_type_from_module_request(module_request);
  520. // 3. If the result of running the module type allowed steps given moduleType and settingsObject is false,
  521. // then run onComplete given null, and return.
  522. if (!settings_object.module_type_allowed(module_type)) {
  523. on_complete->function()(nullptr);
  524. return;
  525. }
  526. // 4. Fetch a single module script given url, fetchClient, destination, options, settingsObject, referrer, moduleRequest, false,
  527. // and onComplete. If performFetch was given, pass it along as well.
  528. fetch_single_module_script(realm, url, fetch_client, destination, options, settings_object, referrer, module_request, TopLevelModule::No, on_complete);
  529. }
  530. // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-the-descendants-of-and-link-a-module-script
  531. void fetch_descendants_of_and_link_a_module_script(JS::Realm& realm,
  532. JavaScriptModuleScript& module_script,
  533. EnvironmentSettingsObject& fetch_client,
  534. Fetch::Infrastructure::Request::Destination destination,
  535. OnFetchScriptComplete on_complete)
  536. {
  537. // 1. Let record be moduleScript's record.
  538. auto* record = module_script.record();
  539. // 2. If record is null, then:
  540. if (!record) {
  541. // 1. Set moduleScript's error to rethrow to moduleScript's parse error.
  542. module_script.set_error_to_rethrow(module_script.parse_error());
  543. // 2. Run onComplete given moduleScript.
  544. on_complete->function()(module_script);
  545. // 3. Return.
  546. return;
  547. }
  548. // 3. Let state be Record { [[ParseError]]: null, [[Destination]]: destination, [[PerformFetch]]: null, [[FetchClient]]: fetchClient }.
  549. auto state = FetchContext { {}, destination, {}, fetch_client };
  550. // FIXME: 4. If performFetch was given, set state.[[PerformFetch]] to performFetch.
  551. // FIXME: These should most likely be steps in the spec.
  552. // NOTE: For reasons beyond my understanding, we cannot use TemporaryExecutionContext here.
  553. // Calling perform_a_microtask_checkpoint() on the fetch_client's responsible_event_loop
  554. // prevents this from functioning properly. HTMLParser::the_end would be run before
  555. // HTMLScriptElement::prepare_script had a chance to setup the callback to mark_done properly,
  556. // resulting in the event loop hanging forever awaiting for the script to be ready for parser
  557. // execution.
  558. realm.vm().push_execution_context(fetch_client.realm_execution_context());
  559. fetch_client.prepare_to_run_callback();
  560. // 5. Let loadingPromise be record.LoadRequestedModules(state).
  561. auto& loading_promise = record->load_requested_modules(realm, state);
  562. // 6. Upon fulfillment of loadingPromise, run the following steps:
  563. WebIDL::upon_fulfillment(loading_promise, [&realm, record, &module_script, on_complete](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  564. // 1. Perform record.Link().
  565. auto linking_result = record->link(realm.vm());
  566. // If this throws an exception, set result's error to rethrow to that exception.
  567. if (linking_result.is_throw_completion())
  568. module_script.set_error_to_rethrow(linking_result.release_error().value().value());
  569. // 2. Run onComplete given moduleScript.
  570. on_complete->function()(module_script);
  571. return JS::js_undefined();
  572. });
  573. // 7. Upon rejection of loadingPromise, run the following steps:
  574. WebIDL::upon_rejection(loading_promise, [&state, &module_script, on_complete](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  575. // 1. If state.[[ParseError]] is not null, set moduleScript's error to rethrow to state.[[ParseError]] and run
  576. // onComplete given moduleScript.
  577. if (state.parse_error != nullptr) {
  578. module_script.set_error_to_rethrow(*state.parse_error);
  579. on_complete->function()(module_script);
  580. }
  581. // 2. Otherwise, run onComplete given null.
  582. else {
  583. on_complete->function()(nullptr);
  584. }
  585. return JS::js_undefined();
  586. });
  587. fetch_client.clean_up_after_running_callback();
  588. realm.vm().pop_execution_context();
  589. }
  590. }