URLSearchParams.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <AK/StringBuilder.h>
  8. #include <AK/Utf8View.h>
  9. #include <LibWeb/URL/URL.h>
  10. #include <LibWeb/URL/URLSearchParams.h>
  11. namespace Web::URL {
  12. String url_encode(const Vector<QueryParam>& pairs, AK::URL::PercentEncodeSet percent_encode_set)
  13. {
  14. StringBuilder builder;
  15. for (size_t i = 0; i < pairs.size(); ++i) {
  16. builder.append(AK::URL::percent_encode(pairs[i].name, percent_encode_set));
  17. builder.append('=');
  18. builder.append(AK::URL::percent_encode(pairs[i].value, percent_encode_set));
  19. if (i != pairs.size() - 1)
  20. builder.append('&');
  21. }
  22. return builder.to_string();
  23. }
  24. Vector<QueryParam> url_decode(StringView input)
  25. {
  26. // 1. Let sequences be the result of splitting input on 0x26 (&).
  27. auto sequences = input.split_view('&');
  28. // 2. Let output be an initially empty list of name-value tuples where both name and value hold a string.
  29. Vector<QueryParam> output;
  30. // 3. For each byte sequence bytes in sequences:
  31. for (auto bytes : sequences) {
  32. // 1. If bytes is the empty byte sequence, then continue.
  33. if (bytes.is_empty())
  34. continue;
  35. StringView name;
  36. StringView value;
  37. // 2. If bytes contains a 0x3D (=), then let name be the bytes from the start of bytes up to but excluding its first 0x3D (=), and let value be the bytes, if any, after the first 0x3D (=) up to the end of bytes. If 0x3D (=) is the first byte, then name will be the empty byte sequence. If it is the last, then value will be the empty byte sequence.
  38. if (auto index = bytes.find('='); index.has_value()) {
  39. name = bytes.substring_view(0, *index);
  40. value = bytes.substring_view(*index + 1);
  41. }
  42. // 3. Otherwise, let name have the value of bytes and let value be the empty byte sequence.
  43. else {
  44. name = bytes;
  45. value = ""sv;
  46. }
  47. // 4. Replace any 0x2B (+) in name and value with 0x20 (SP).
  48. auto space_decoded_name = name.replace("+"sv, " "sv, true);
  49. // 5. Let nameString and valueString be the result of running UTF-8 decode without BOM on the percent-decoding of name and value, respectively.
  50. auto name_string = AK::URL::percent_decode(space_decoded_name);
  51. auto value_string = AK::URL::percent_decode(value);
  52. output.empend(move(name_string), move(value_string));
  53. }
  54. return output;
  55. }
  56. // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  57. // https://url.spec.whatwg.org/#urlsearchparams-initialize
  58. DOM::ExceptionOr<NonnullRefPtr<URLSearchParams>> URLSearchParams::create_with_global_object(Bindings::WindowObject&, Variant<Vector<Vector<String>>, OrderedHashMap<String, String>, String> const& init)
  59. {
  60. // 1. If init is a string and starts with U+003F (?), then remove the first code point from init.
  61. // NOTE: We do this when we know that it's a string on step 3 of initialization.
  62. // 2. Initialize this with init.
  63. // URLSearchParams init from this point forward
  64. // 1. If init is a sequence, then for each pair in init:
  65. if (init.has<Vector<Vector<String>>>()) {
  66. auto const& init_sequence = init.get<Vector<Vector<String>>>();
  67. Vector<QueryParam> list;
  68. list.ensure_capacity(init_sequence.size());
  69. for (auto const& pair : init_sequence) {
  70. // a. If pair does not contain exactly two items, then throw a TypeError.
  71. if (pair.size() != 2)
  72. return DOM::SimpleException { DOM::SimpleExceptionType::TypeError, String::formatted("Expected only 2 items in pair, got {}", pair.size()) };
  73. // b. Append a new name-value pair whose name is pair’s first item, and value is pair’s second item, to query’s list.
  74. list.append(QueryParam { .name = pair[0], .value = pair[1] });
  75. }
  76. return URLSearchParams::create(move(list));
  77. }
  78. // 2. Otherwise, if init is a record, then for each name → value of init, append a new name-value pair whose name is name and value is value, to query’s list.
  79. if (init.has<OrderedHashMap<String, String>>()) {
  80. auto const& init_record = init.get<OrderedHashMap<String, String>>();
  81. Vector<QueryParam> list;
  82. list.ensure_capacity(init_record.size());
  83. for (auto const& pair : init_record)
  84. list.append(QueryParam { .name = pair.key, .value = pair.value });
  85. return URLSearchParams::create(move(list));
  86. }
  87. // 3. Otherwise:
  88. // a. Assert: init is a string.
  89. // NOTE: `get` performs `VERIFY(has<T>())`
  90. auto const& init_string = init.get<String>();
  91. // See NOTE at the start of this function.
  92. StringView stripped_init = init_string.substring_view(init_string.starts_with('?'));
  93. // b. Set query’s list to the result of parsing init.
  94. return URLSearchParams::create(url_decode(stripped_init));
  95. }
  96. void URLSearchParams::append(String const& name, String const& value)
  97. {
  98. // 1. Append a new name-value pair whose name is name and value is value, to list.
  99. m_list.empend(name, value);
  100. // 2. Update this.
  101. update();
  102. }
  103. void URLSearchParams::update()
  104. {
  105. // 1. If query’s URL object is null, then return.
  106. if (m_url.is_null())
  107. return;
  108. // 2. Let serializedQuery be the serialization of query’s list.
  109. auto serialized_query = to_string();
  110. // 3. If serializedQuery is the empty string, then set serializedQuery to null.
  111. if (serialized_query.is_empty())
  112. serialized_query = {};
  113. // 4. Set query’s URL object’s URL’s query to serializedQuery.
  114. m_url->set_query({}, move(serialized_query));
  115. }
  116. void URLSearchParams::delete_(String const& name)
  117. {
  118. // 1. Remove all name-value pairs whose name is name from list.
  119. m_list.remove_all_matching([&name](auto& entry) {
  120. return entry.name == name;
  121. });
  122. // 2. Update this.
  123. update();
  124. }
  125. String URLSearchParams::get(String const& name)
  126. {
  127. // return the value of the first name-value pair whose name is name in this’s list, if there is such a pair, and null otherwise.
  128. auto result = m_list.find_if([&name](auto& entry) {
  129. return entry.name == name;
  130. });
  131. if (result.is_end())
  132. return {};
  133. return result->value;
  134. }
  135. // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  136. Vector<String> URLSearchParams::get_all(String const& name)
  137. {
  138. // return the values of all name-value pairs whose name is name, in this’s list, in list order, and the empty sequence otherwise.
  139. Vector<String> values;
  140. for (auto& entry : m_list) {
  141. if (entry.name == name)
  142. values.append(entry.value);
  143. }
  144. return values;
  145. }
  146. bool URLSearchParams::has(String const& name)
  147. {
  148. // return true if there is a name-value pair whose name is name in this’s list, and false otherwise.
  149. return !m_list.find_if([&name](auto& entry) {
  150. return entry.name == name;
  151. })
  152. .is_end();
  153. }
  154. void URLSearchParams::set(const String& name, const String& value)
  155. {
  156. // 1. If this’s list contains any name-value pairs whose name is name, then set the value of the first such name-value pair to value and remove the others.
  157. auto existing = m_list.find_if([&name](auto& entry) {
  158. return entry.name == name;
  159. });
  160. if (!existing.is_end()) {
  161. existing->value = value;
  162. m_list.remove_all_matching([&name, &existing](auto& entry) {
  163. return &entry != &*existing && entry.name == name;
  164. });
  165. }
  166. // 2. Otherwise, append a new name-value pair whose name is name and value is value, to this’s list.
  167. else {
  168. m_list.empend(name, value);
  169. }
  170. // 3. Update this.
  171. update();
  172. }
  173. void URLSearchParams::sort()
  174. {
  175. // 1. Sort all name-value pairs, if any, by their names. Sorting must be done by comparison of code units. The relative order between name-value pairs with equal names must be preserved.
  176. quick_sort(m_list.begin(), m_list.end(), [](auto& a, auto& b) {
  177. Utf8View a_code_points { a.name };
  178. Utf8View b_code_points { b.name };
  179. if (a_code_points.starts_with(b_code_points))
  180. return false;
  181. if (b_code_points.starts_with(a_code_points))
  182. return true;
  183. for (auto k = a_code_points.begin(), l = b_code_points.begin();
  184. k != a_code_points.end() && l != b_code_points.end();
  185. ++k, ++l) {
  186. if (*k != *l) {
  187. if (*k < *l) {
  188. return true;
  189. } else {
  190. return false;
  191. }
  192. }
  193. }
  194. VERIFY_NOT_REACHED();
  195. });
  196. // 2. Update this.
  197. update();
  198. }
  199. String URLSearchParams::to_string()
  200. {
  201. // return the serialization of this’s list.
  202. return url_encode(m_list, AK::URL::PercentEncodeSet::ApplicationXWWWFormUrlencoded);
  203. }
  204. JS::ThrowCompletionOr<void> URLSearchParams::for_each(ForEachCallback callback)
  205. {
  206. for (auto i = 0u; i < m_list.size(); ++i) {
  207. auto& query_param = m_list[i]; // We are explicitly iterating over the indices here as the callback might delete items from the list
  208. TRY(callback(query_param.name, query_param.value));
  209. }
  210. return {};
  211. }
  212. }