Fetching.cpp 55 KB

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