1use std::cell::{Cell, RefCell};
11use std::rc::Rc;
12
13use lol_html::{HtmlRewriter, Settings, element, end_tag};
14
15use crate::error::LivewireError;
16
17pub fn insert_attributes(html: &str, attributes: &[(String, String)]) -> Result<String, LivewireError> {
30 if attributes.is_empty() {
31 return Ok(html.to_owned());
32 }
33
34 let start = first_element_start(html)?;
35
36 let mut insert_at = start + 1;
37 let bytes = html.as_bytes();
38 while insert_at < bytes.len() && !is_tag_name_terminator(bytes[insert_at]) {
39 insert_at += 1;
40 }
41
42 let mut output = String::with_capacity(
43 html.len()
44 + attributes
45 .iter()
46 .map(|(name, value)| name.len() + value.len() + 4)
47 .sum::<usize>(),
48 );
49
50 output.push_str(&html[..insert_at]);
51
52 for (name, value) in attributes {
53 output.push(' ');
54 output.push_str(name);
55 output.push_str("=\"");
56 output.push_str(&escape_attribute(value));
57 output.push('"');
58 }
59
60 output.push_str(&html[insert_at..]);
61
62 Ok(output)
63}
64
65pub fn escape_attribute(value: &str) -> String {
71 const NEEDS_ESCAPE: [bool; 256] = {
72 let mut table = [false; 256];
73 table[b'&' as usize] = true;
74 table[b'<' as usize] = true;
75 table[b'>' as usize] = true;
76 table[b'"' as usize] = true;
77 table[b'\'' as usize] = true;
78 table
79 };
80
81 if !value.bytes().any(|byte| NEEDS_ESCAPE[byte as usize]) {
82 return value.to_owned();
83 }
84
85 let mut escaped = String::with_capacity(value.len() + 16);
86
87 for character in value.chars() {
88 match character {
89 '&' => escaped.push_str("&"),
90 '<' => escaped.push_str("<"),
91 '>' => escaped.push_str(">"),
92 '"' => escaped.push_str("""),
93 '\'' => escaped.push_str("'"),
94 other => escaped.push(other),
95 }
96 }
97
98 escaped
99}
100
101pub fn count_root_elements(html: &str) -> usize {
107 let state = Rc::new(RefCell::new(RootCount::default()));
108 let element_state = Rc::clone(&state);
109
110 let mut rewriter = HtmlRewriter::new(
111 Settings {
112 element_content_handlers: vec![element!("*", move |element| {
113 let opens = element.can_have_content() && !element.is_self_closing();
114
115 {
116 let mut state = element_state.borrow_mut();
117
118 if state.depth == 0 {
119 state.count += 1;
120 }
121
122 if opens {
123 state.depth += 1;
124 }
125 }
126
127 if opens {
128 let end_state = Rc::clone(&element_state);
129
130 element.on_end_tag(end_tag!(move |_| {
131 let mut state = end_state.borrow_mut();
132 state.depth = state.depth.saturating_sub(1);
133
134 Ok(())
135 }))?;
136 }
137
138 Ok(())
139 })],
140 ..Settings::new()
141 },
142 |_: &[u8]| {},
143 );
144
145 let _ = rewriter.write(html.as_bytes());
146 let _ = rewriter.end();
147
148 let state = state.borrow();
149
150 state.count
151}
152
153#[derive(Default)]
155struct RootCount {
156 depth: usize,
158 count: usize,
160}
161
162fn first_element_start(html: &str) -> Result<usize, LivewireError> {
164 let start = Rc::new(Cell::new(None));
165 let element_start = Rc::clone(&start);
166
167 let mut rewriter = HtmlRewriter::new(
168 Settings {
169 element_content_handlers: vec![element!("*", move |element| {
170 if element_start.get().is_none() {
171 element_start.set(Some(element.source_location().bytes().start));
172 }
173
174 Ok(())
175 })],
176 ..Settings::new()
177 },
178 |_: &[u8]| {},
179 );
180
181 rewriter
182 .write(html.as_bytes())
183 .map_err(|error| LivewireError::MalformedPayload(error.to_string()))?;
184 rewriter
185 .end()
186 .map_err(|error| LivewireError::MalformedPayload(error.to_string()))?;
187
188 start.get().ok_or(LivewireError::RootTagMissing)
189}
190
191fn is_tag_name_terminator(byte: u8) -> bool {
193 matches!(byte, b' ' | b'\t' | b'\n' | b'\r' | b'\x0c' | b'/' | b'>')
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199
200 fn attributes(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
201 pairs
202 .iter()
203 .map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
204 .collect()
205 }
206
207 #[test]
208 fn inserts_into_a_plain_root_element() {
209 let html = insert_attributes("<div></div>", &attributes(&[("wire:id", "abc")])).unwrap();
210
211 assert_eq!(html, "<div wire:id=\"abc\"></div>");
212 }
213
214 #[test]
215 fn inserts_before_existing_attributes() {
216 let html = insert_attributes(
217 "<div class=\"a\" data-b='c' hidden>text</div>",
218 &attributes(&[("wire:id", "abc"), ("wire:name", "counter")]),
219 )
220 .unwrap();
221
222 assert_eq!(
223 html,
224 "<div wire:id=\"abc\" wire:name=\"counter\" class=\"a\" data-b='c' hidden>text</div>"
225 );
226 }
227
228 #[test]
229 fn preserves_every_other_byte() {
230 let source = concat!(
231 "<div class=\"a\" >\n",
232 " <script>if (a < b && c > d) { x = \"<span>\"; }</script>\n",
233 " <!-- keep \"quotes\" & <tags> -->\n",
234 " <img src=\"x.png\" />\n",
235 "</div>\n",
236 );
237
238 let html = insert_attributes(source, &attributes(&[("wire:id", "abc")])).unwrap();
239
240 assert_eq!(html, source.replacen("<div", "<div wire:id=\"abc\"", 1));
241 }
242
243 #[test]
244 fn skips_leading_whitespace() {
245 let html = insert_attributes("\n\n <div></div>", &attributes(&[("wire:id", "abc")])).unwrap();
246
247 assert_eq!(html, "\n\n <div wire:id=\"abc\"></div>");
248 }
249
250 #[test]
251 fn skips_leading_comments_and_text() {
252 let html = insert_attributes(
253 "<!-- hello -->\n text\n <section id=\"s\"></section>",
254 &attributes(&[("wire:id", "abc")]),
255 )
256 .unwrap();
257
258 assert_eq!(
259 html,
260 "<!-- hello -->\n text\n <section wire:id=\"abc\" id=\"s\"></section>"
261 );
262 }
263
264 #[test]
265 fn targets_a_self_closing_element() {
266 let html = insert_attributes("<img src=\"x.png\" />", &attributes(&[("wire:id", "abc")])).unwrap();
267
268 assert_eq!(html, "<img wire:id=\"abc\" src=\"x.png\" />");
269 }
270
271 #[test]
272 fn missing_root_element_is_an_error() {
273 assert_eq!(
274 insert_attributes("", &attributes(&[("wire:id", "abc")])),
275 Err(LivewireError::RootTagMissing)
276 );
277 assert_eq!(
278 insert_attributes("just some text", &attributes(&[("wire:id", "abc")])),
279 Err(LivewireError::RootTagMissing)
280 );
281 assert_eq!(
282 insert_attributes("<!doctype html><!-- c -->", &attributes(&[("wire:id", "abc")])),
283 Err(LivewireError::RootTagMissing)
284 );
285 }
286
287 #[test]
288 fn empty_attributes_return_the_input_unchanged() {
289 assert_eq!(insert_attributes("<div></div>", &[]).unwrap(), "<div></div>");
290 assert_eq!(insert_attributes("", &[]).unwrap(), "");
291 }
292
293 #[test]
294 fn escapes_every_character_php_escapes() {
295 assert_eq!(escape_attribute("&"), "&");
296 assert_eq!(escape_attribute("<"), "<");
297 assert_eq!(escape_attribute(">"), ">");
298 assert_eq!(escape_attribute("\""), """);
299 assert_eq!(escape_attribute("'"), "'");
300 }
301
302 #[test]
303 fn leaves_everything_else_alone() {
304 assert_eq!(escape_attribute("a/b=c d?e#f"), "a/b=c d?e#f");
305 assert_eq!(escape_attribute("ação"), "ação");
306 assert_eq!(escape_attribute(""), "");
307 }
308
309 #[test]
310 fn does_not_double_escape() {
311 assert_eq!(escape_attribute("&"), "&amp;");
312 }
313
314 #[test]
315 fn escapes_real_attribute_values() {
316 let html = insert_attributes(
317 "<div></div>",
318 &attributes(&[
319 ("data-quote", "\""),
320 ("data-apostrophe", "'"),
321 ("data-amp", "&"),
322 ("data-lt", "<"),
323 ("data-gt", ">"),
324 ]),
325 )
326 .unwrap();
327
328 assert_eq!(
329 html,
330 "<div data-quote=\""\" data-apostrophe=\"'\" data-amp=\"&\" data-lt=\"<\" data-gt=\">\"></div>"
331 );
332 }
333
334 #[test]
335 fn escapes_a_snapshot_json_value() {
336 let snapshot = r#"{"data":{"count":1},"memo":{"id":"a","name":"counter"},"checksum":"ab<&"}"#;
337
338 let html = insert_attributes("<div></div>", &attributes(&[("wire:snapshot", snapshot)])).unwrap();
339
340 assert_eq!(
341 html,
342 "<div wire:snapshot=\"{"data":{"count":1},"memo":{"id":"a","name":"counter"},"checksum":"ab<&"}\"></div>"
343 );
344 }
345
346 #[test]
347 fn counts_sibling_roots() {
348 assert_eq!(count_root_elements("<div></div><div></div>"), 2);
349 }
350
351 #[test]
352 fn counts_nested_markup_as_one_root() {
353 assert_eq!(count_root_elements("<div><span></span></div>"), 1);
354 }
355
356 #[test]
357 fn ignores_leading_text() {
358 assert_eq!(count_root_elements("text<div></div>"), 1);
359 }
360
361 #[test]
362 fn ignores_comments() {
363 assert_eq!(count_root_elements("<!-- c --><div></div>"), 1);
364 }
365
366 #[test]
367 fn counts_void_elements_as_roots() {
368 assert_eq!(count_root_elements("<img src=\"x\"><br>"), 2);
369 assert_eq!(count_root_elements("<img src=\"x\"><div></div>"), 2);
370 }
371
372 #[test]
373 fn counts_nothing_in_empty_markup() {
374 assert_eq!(count_root_elements(""), 0);
375 assert_eq!(count_root_elements(" <!-- c --> text"), 0);
376 }
377}