ImportMap.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /*
  2. * Copyright (c) 2024, Jamie Mansfield <jmansfield@cadixdev.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Console.h>
  7. #include <LibJS/Runtime/ConsoleObject.h>
  8. #include <LibWeb/Bindings/HostDefined.h>
  9. #include <LibWeb/DOMURL/DOMURL.h>
  10. #include <LibWeb/HTML/Scripting/Fetching.h>
  11. #include <LibWeb/HTML/Scripting/ImportMap.h>
  12. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  13. #include <LibWeb/Infra/JSON.h>
  14. namespace Web::HTML {
  15. // https://html.spec.whatwg.org/multipage/webappapis.html#parse-an-import-map-string
  16. WebIDL::ExceptionOr<ImportMap> parse_import_map_string(JS::Realm& realm, ByteString const& input, URL::URL base_url)
  17. {
  18. HTML::TemporaryExecutionContext execution_context { Bindings::host_defined_environment_settings_object(realm) };
  19. // 1. Let parsed be the result of parsing a JSON string to an Infra value given input.
  20. auto parsed = TRY(Infra::parse_json_string_to_javascript_value(realm, input));
  21. // 2. If parsed is not an ordered map, then throw a TypeError indicating that the top-level value needs to be a JSON object.
  22. if (!parsed.is_object())
  23. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("The top-level value of an importmap needs to be a JSON object.").release_value_but_fixme_should_propagate_errors() };
  24. auto& parsed_object = parsed.as_object();
  25. // 3. Let sortedAndNormalizedImports be an empty ordered map.
  26. ModuleSpecifierMap sorted_and_normalised_imports;
  27. // 4. If parsed["imports"] exists, then:
  28. if (TRY(parsed_object.has_property("imports"))) {
  29. auto imports = TRY(parsed_object.get("imports"));
  30. // If parsed["imports"] is not an ordered map, then throw a TypeError indicating that the value for the "imports" top-level key needs to be a JSON object.
  31. if (!imports.is_object())
  32. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("The 'imports' top-level value of an importmap needs to be a JSON object.").release_value_but_fixme_should_propagate_errors() };
  33. // Set sortedAndNormalizedImports to the result of sorting and normalizing a module specifier map given parsed["imports"] and baseURL.
  34. sorted_and_normalised_imports = TRY(sort_and_normalise_module_specifier_map(realm, imports.as_object(), base_url));
  35. }
  36. // 5. Let sortedAndNormalizedScopes be an empty ordered map.
  37. HashMap<URL::URL, ModuleSpecifierMap> sorted_and_normalised_scopes;
  38. // 6. If parsed["scopes"] exists, then:
  39. if (TRY(parsed_object.has_property("scopes"))) {
  40. auto scopes = TRY(parsed_object.get("scopes"));
  41. // If parsed["scopes"] is not an ordered map, then throw a TypeError indicating that the value for the "scopes" top-level key needs to be a JSON object.
  42. if (!scopes.is_object())
  43. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("The 'scopes' top-level value of an importmap needs to be a JSON object.").release_value_but_fixme_should_propagate_errors() };
  44. // Set sortedAndNormalizedScopes to the result of sorting and normalizing scopes given parsed["scopes"] and baseURL.
  45. sorted_and_normalised_scopes = TRY(sort_and_normalise_scopes(realm, scopes.as_object(), base_url));
  46. }
  47. // 7. If parsed's keys contains any items besides "imports" or "scopes", then the user agent should report a warning to the console indicating that an invalid top-level key was present in the import map.
  48. for (auto& key : parsed_object.shape().property_table().keys()) {
  49. if (key.as_string() == "imports" || key.as_string() == "imports")
  50. continue;
  51. auto& console = realm.intrinsics().console_object()->console();
  52. console.output_debug_message(JS::Console::LogLevel::Warn,
  53. TRY_OR_THROW_OOM(realm.vm(), String::formatted("An invalid top-level key ({}) was present in the import map", key.as_string())));
  54. }
  55. // 8. Return an import map whose imports are sortedAndNormalizedImports and whose scopes are sortedAndNormalizedScopes.
  56. ImportMap import_map;
  57. import_map.set_imports(sorted_and_normalised_imports);
  58. return import_map;
  59. }
  60. // https://html.spec.whatwg.org/multipage/webappapis.html#normalizing-a-specifier-key
  61. WebIDL::ExceptionOr<Optional<DeprecatedFlyString>> normalise_specifier_key(JS::Realm& realm, DeprecatedFlyString specifier_key, URL::URL base_url)
  62. {
  63. // 1. If specifierKey is the empty string, then:
  64. if (specifier_key.is_empty()) {
  65. // 1. The user agent may report a warning to the console indicating that specifier keys may not be the empty string.
  66. auto& console = realm.intrinsics().console_object()->console();
  67. console.output_debug_message(JS::Console::LogLevel::Warn,
  68. TRY_OR_THROW_OOM(realm.vm(), String::formatted("Specifier keys may not be empty")));
  69. // 2. Return null.
  70. return Optional<DeprecatedFlyString> {};
  71. }
  72. // 2. Let url be the result of resolving a URL-like module specifier, given specifierKey and baseURL.
  73. auto url = resolve_url_like_module_specifier(specifier_key, base_url);
  74. // 3. If url is not null, then return the serialization of url.
  75. if (url.has_value())
  76. return url->serialize();
  77. // 4. Return specifierKey.
  78. return specifier_key;
  79. }
  80. // https://html.spec.whatwg.org/multipage/webappapis.html#sorting-and-normalizing-a-module-specifier-map
  81. WebIDL::ExceptionOr<ModuleSpecifierMap> sort_and_normalise_module_specifier_map(JS::Realm& realm, JS::Object& original_map, URL::URL base_url)
  82. {
  83. // 1. Let normalized be an empty ordered map.
  84. ModuleSpecifierMap normalised;
  85. // 2. For each specifierKey → value of originalMap:
  86. for (auto& specifier_key : original_map.shape().property_table().keys()) {
  87. auto value = TRY(original_map.get(specifier_key.as_string()));
  88. // 1. Let normalizedSpecifierKey be the result of normalizing a specifier key given specifierKey and baseURL.
  89. auto normalised_specifier_key = TRY(normalise_specifier_key(realm, specifier_key.as_string(), base_url));
  90. // 2. If normalizedSpecifierKey is null, then continue.
  91. if (!normalised_specifier_key.has_value())
  92. continue;
  93. // 3. If value is not a string, then:
  94. if (!value.is_string()) {
  95. // 1. The user agent may report a warning to the console indicating that addresses need to be strings.
  96. auto& console = realm.intrinsics().console_object()->console();
  97. console.output_debug_message(JS::Console::LogLevel::Warn,
  98. TRY_OR_THROW_OOM(realm.vm(), String::formatted("Addresses need to be strings")));
  99. // 2. Set normalized[normalizedSpecifierKey] to null.
  100. normalised.set(normalised_specifier_key.value(), {});
  101. // 3. Continue.
  102. continue;
  103. }
  104. // 4. Let addressURL be the result of resolving a URL-like module specifier given value and baseURL.
  105. auto address_url = resolve_url_like_module_specifier(value.as_string().byte_string(), base_url);
  106. // 5. If addressURL is null, then:
  107. if (!address_url.has_value()) {
  108. // 1. The user agent may report a warning to the console indicating that the address was invalid.
  109. auto& console = realm.intrinsics().console_object()->console();
  110. console.output_debug_message(JS::Console::LogLevel::Warn,
  111. TRY_OR_THROW_OOM(realm.vm(), String::formatted("Address was invalid")));
  112. // 2. Set normalized[normalizedSpecifierKey] to null.
  113. normalised.set(normalised_specifier_key.value(), {});
  114. // 3. Continue.
  115. continue;
  116. }
  117. // 6. If specifierKey ends with U+002F (/), and the serialization of addressURL does not end with U+002F (/), then:
  118. if (specifier_key.as_string().ends_with("/"sv) && !address_url->serialize().ends_with("/"sv)) {
  119. // 1. The user agent may report a warning to the console indicating that an invalid address was given for the specifier key specifierKey; since specifierKey ends with a slash, the address needs to as well.
  120. auto& console = realm.intrinsics().console_object()->console();
  121. console.output_debug_message(JS::Console::LogLevel::Warn,
  122. TRY_OR_THROW_OOM(realm.vm(), String::formatted("An invalid address was given for the specifier key ({}); since specifierKey ends with a slash, the address needs to as well", specifier_key.as_string())));
  123. // 2. Set normalized[normalizedSpecifierKey] to null.
  124. normalised.set(normalised_specifier_key.value(), {});
  125. // 3. Continue.
  126. continue;
  127. }
  128. // 7. Set normalized[normalizedSpecifierKey] to addressURL.
  129. normalised.set(normalised_specifier_key.value(), address_url.value());
  130. }
  131. // 3. Return the result of sorting in descending order normalized, with an entry a being less than an entry b if a's key is code unit less than b's key.
  132. return normalised;
  133. }
  134. // https://html.spec.whatwg.org/multipage/webappapis.html#sorting-and-normalizing-scopes
  135. WebIDL::ExceptionOr<HashMap<URL::URL, ModuleSpecifierMap>> sort_and_normalise_scopes(JS::Realm& realm, JS::Object& original_map, URL::URL base_url)
  136. {
  137. // 1. Let normalized be an empty ordered map.
  138. HashMap<URL::URL, ModuleSpecifierMap> normalised;
  139. // 2. For each scopePrefix → potentialSpecifierMap of originalMap:
  140. for (auto& scope_prefix : original_map.shape().property_table().keys()) {
  141. auto potential_specifier_map = TRY(original_map.get(scope_prefix.as_string()));
  142. // 1. If potentialSpecifierMap is not an ordered map, then throw a TypeError indicating that the value of the scope with prefix scopePrefix needs to be a JSON object.
  143. if (!potential_specifier_map.is_object())
  144. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, String::formatted("The value of the scope with the prefix '{}' needs to be a JSON object.", scope_prefix.as_string()).release_value_but_fixme_should_propagate_errors() };
  145. // 2. Let scopePrefixURL be the result of URL parsing scopePrefix with baseURL.
  146. auto scope_prefix_url = DOMURL::parse(scope_prefix.as_string(), base_url);
  147. // 3. If scopePrefixURL is failure, then:
  148. if (!scope_prefix_url.is_valid()) {
  149. // 1. The user agent may report a warning to the console that the scope prefix URL was not parseable.
  150. auto& console = realm.intrinsics().console_object()->console();
  151. console.output_debug_message(JS::Console::LogLevel::Warn,
  152. TRY_OR_THROW_OOM(realm.vm(), String::formatted("The scope prefix URL ({}) was not parseable", scope_prefix.as_string())));
  153. // 2. Continue.
  154. continue;
  155. }
  156. // 4. Let normalizedScopePrefix be the serialization of scopePrefixURL.
  157. auto normalised_scope_prefix = scope_prefix_url.serialize();
  158. // 5. Set normalized[normalizedScopePrefix] to the result of sorting and normalizing a module specifier map given potentialSpecifierMap and baseURL.
  159. normalised.set(normalised_scope_prefix, TRY(sort_and_normalise_module_specifier_map(realm, potential_specifier_map.as_object(), base_url)));
  160. }
  161. // 3. Return the result of sorting in descending order normalized, with an entry a being less than an entry b if a's key is code unit less than b's key.
  162. return normalised;
  163. }
  164. }