1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568

mod script_element {


use self::super::super::super::super::util::{concat_path, read_file};
use std::path::{PathBuf, is_separator as is_path_separator};
use self::super::{WrappedElement, ElementClass};
use self::super::super::super::super::Error;
use std::borrow::Cow;
use serde::de;
use std::fmt;


lazy_static! {
    static ref SCRIPT_LINK_HEAD: &'static str = include_str!("../../../../../../assets/element_wrappers/script/link.head").trim();
    static ref SCRIPT_LINK_FOOT: &'static str = include_str!("../../../../../../assets/element_wrappers/script/link.foot").trim_start();

    static ref SCRIPT_LITERAL_HEAD: &'static str = include_str!("../../../../../../assets/element_wrappers/script/literal.head").trim_start();
    static ref SCRIPT_LITERAL_FOOT: &'static str = include_str!("../../../../../../assets/element_wrappers/script/literal.foot");
}


/// A script specifier.
///
/// Can be a link or a literal, and a literal can be indirectly loaded from a file.
///
/// Consult the documentation for [`load()`](#fn.load) on handling filesystem interaxion.
///
/// # Deserialisation
///
/// There are two serialised forms, a verbose one:
///
/// ```
/// # extern crate toml;
/// # extern crate bloguen;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # use bloguen::ops::ScriptElement;
/// #[derive(Deserialize, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
/// struct ScriptContainer {
///     pub script: Vec<ScriptElement>,
/// }
///
/// # fn main() {
/// let script_toml =
///     "[[script]]
///      class = 'link'
///      data = '/content/assets/syllable.js'
///
///      [[script]]
///      class = 'literal'
///      data = 'document.getElementById(\"title\").innerText = \"Наган\";'
///
///      [[script]]
///      class = 'file'
///      data = 'MathJax-config.js'";
///
/// let ScriptContainer { script } = toml::from_str(script_toml).unwrap();
/// assert_eq!(&script,
///            &[ScriptElement::from_link("/content/assets/syllable.js"),
///              ScriptElement::from_literal("document.getElementById(\"title\").innerText = \"Наган\";"),
///              ScriptElement::from_path("MathJax-config.js")]);
/// # }
/// ```
///
/// And a compact one (the "literal" tag may be omitted if the content doesn't contain any colons):
///
/// ```
/// # extern crate toml;
/// # extern crate bloguen;
/// # #[macro_use]
/// # extern crate serde_derive;
/// # use bloguen::ops::ScriptElement;
/// #[derive(Deserialize, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
/// struct ScriptContainer {
///     pub scripts: Vec<ScriptElement>,
/// }
///
/// # fn main() {
/// let scripts_toml =
///     "scripts = [
///          'link:/content/assets/syllable.js',
///          'literal:document.getElementById(\"title\").innerText = \"Наган\";',
///          'file:MathJax-config.js',
///      ]";
///
/// let ScriptContainer { scripts } = toml::from_str(scripts_toml).unwrap();
/// assert_eq!(&scripts,
///            &[ScriptElement::from_link("/content/assets/syllable.js"),
///              ScriptElement::from_literal("document.getElementById(\"title\").innerText = \"Наган\";"),
///              ScriptElement::from_path("MathJax-config.js")]);
/// # }
/// ```
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct ScriptElement {
    class: ElementClass,
    data: Cow<'static, str>,
}

impl ScriptElement {
    /// Create a script element linking to an external resource.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bloguen::ops::{WrappedElement, ScriptElement};
    /// let lonk = ScriptElement::from_link("/content/assets/syllable.js");
    /// assert_eq!(
    ///     format!("{}{}{}", lonk.head(), lonk.content(), lonk.foot()),
    ///     "<script type=\"text/javascript\" src=\"/content/assets/syllable.js\"></script>\n")
    /// ```
    pub fn from_link<Dt: Into<Cow<'static, str>>>(link: Dt) -> ScriptElement {
        ScriptElement::from_link_impl(link.into())
    }

    fn from_link_impl(link: Cow<'static, str>) -> ScriptElement {
        ScriptElement {
            class: ElementClass::Link,
            data: link,
        }
    }

    /// Create a script element including the specified literal literally.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bloguen::ops::{WrappedElement, ScriptElement};
    /// let lit = ScriptElement::from_literal("document.getElementById(\"title\").innerText = \"Наган\";");
    /// assert_eq!(
    ///     format!("{}{}{}", lit.head(), lit.content(), lit.foot()),
    ///     "<script type=\"text/javascript\">\n\ndocument.getElementById(\"title\").innerText = \"Наган\";\n\n</script>\n")
    /// ```
    pub fn from_literal<Dt: Into<Cow<'static, str>>>(literal: Dt) -> ScriptElement {
        ScriptElement::from_literal_impl(literal.into())
    }

    fn from_literal_impl(literal: Cow<'static, str>) -> ScriptElement {
        ScriptElement {
            class: ElementClass::Literal,
            data: literal,
        }
    }

    /// Create a script element pointing to the specified relative path.
    ///
    /// Consult [`load()`](#fn.load) documentation for more data.
    ///
    /// # Examples
    ///
    /// Given `$ROOT/MathJax-config.js` containing:
    ///
    /// ```js
    /// MathJax.Hub.Config({
    ///   jax: ["input/AsciiMath", "output/HTML-CSS"],
    ///   extensions: ["asciimath2jax.js"],
    ///   asciimath2jax: {
    ///     delimiters: [['[​[​', '​]​]']],
    ///     preview: "[[maths]]"
    ///   },
    ///   AsciiMath: {
    ///     decimal: "."
    ///   },
    ///   "HTML-CSS": {
    ///     undefinedFamily: "STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif"
    ///   }
    /// });
    /// ```
    ///
    /// The following holds:
    ///
    /// ```
    /// # use bloguen::ops::{WrappedElement, ScriptElement};
    /// # use std::fs::{self, File};
    /// # use std::env::temp_dir;
    /// # use std::io::Write;
    /// # use bloguen::Error;
    /// # let root = temp_dir().join("bloguen-doctest").join("ops-output-wrapped_element-script_element-from_path");
    /// # fs::create_dir_all(&root).unwrap();
    /// # File::create(root.join("MathJax-config.js")).unwrap().write_all("\
    /// #     MathJax.Hub.Config({\n\
    /// #       jax: [\"input/AsciiMath\", \"output/HTML-CSS\"],\n\
    /// #       extensions: [\"asciimath2jax.js\"],\n\
    /// #       asciimath2jax: {\n\
    /// #         delimiters: [['[​[​', '​]​]']],\n\
    /// #         preview: \"[[maths]]\"\n\
    /// #       },\n\
    /// #       AsciiMath: {\n\
    /// #         decimal: \".\"\n\
    /// #       },\n\
    /// #       \"HTML-CSS\": {\n\
    /// #         undefinedFamily: \"STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif\"\n\
    /// #       }\n\
    /// #     });\n\
    /// # ".as_bytes()).unwrap();
    /// # /*
    /// let root: PathBuf = /* obtained elsewhere */;
    /// # */
    ///
    /// let mut lit_p = ScriptElement::from_path("MathJax-config.js");
    /// assert_eq!(lit_p.load(&("$ROOT".to_string(), root.clone())), Ok(()));
    /// assert_eq!(format!("{}{}{}", lit_p.head(), lit_p.content(), lit_p.foot()),
    /// "<script type=\"text/javascript\">\n\n\
    ///     MathJax.Hub.Config({\n\
    ///       jax: [\"input/AsciiMath\", \"output/HTML-CSS\"],\n\
    ///       extensions: [\"asciimath2jax.js\"],\n\
    ///       asciimath2jax: {\n\
    ///         delimiters: [['[​[​', '​]​]']],\n\
    ///         preview: \"[[maths]]\"\n\
    ///       },\n\
    ///       AsciiMath: {\n\
    ///         decimal: \".\"\n\
    ///       },\n\
    ///       \"HTML-CSS\": {\n\
    ///         undefinedFamily: \"STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif\"\n\
    ///       }\n\
    ///     });\n\
    /// \n\n</script>\n");
    /// ```
    pub fn from_path<Dt: Into<Cow<'static, str>>>(path: Dt) -> ScriptElement {
        ScriptElement::from_path_impl(path.into())
    }

    fn from_path_impl(path: Cow<'static, str>) -> ScriptElement {
        ScriptElement {
            class: ElementClass::File,
            data: path.into(),
        }
    }

    /// Create a literal script element from the contents of the specified file.
    ///
    /// # Examples
    ///
    /// Given `$ROOT/MathJax-config.js` containing:
    ///
    /// ```js
    /// MathJax.Hub.Config({
    ///   jax: ["input/AsciiMath", "output/HTML-CSS"],
    ///   extensions: ["asciimath2jax.js"],
    ///   asciimath2jax: {
    ///     delimiters: [['[​[​', '​]​]']],
    ///     preview: "[[maths]]"
    ///   },
    ///   AsciiMath: {
    ///     decimal: "."
    ///   },
    ///   "HTML-CSS": {
    ///     undefinedFamily: "STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif"
    ///   }
    /// });
    /// ```
    ///
    /// The following holds:
    ///
    /// ```
    /// # use bloguen::ops::{WrappedElement, ScriptElement};
    /// # use std::fs::{self, File};
    /// # use std::env::temp_dir;
    /// # use std::io::Write;
    /// # use bloguen::Error;
    /// # let root = temp_dir().join("bloguen-doctest").join("ops-output-wrapped_element-script_element-from_file");
    /// # fs::create_dir_all(&root).unwrap();
    /// # File::create(root.join("MathJax-config.js")).unwrap().write_all("\
    /// #     MathJax.Hub.Config({\n\
    /// #       jax: [\"input/AsciiMath\", \"output/HTML-CSS\"],\n\
    /// #       extensions: [\"asciimath2jax.js\"],\n\
    /// #       asciimath2jax: {\n\
    /// #         delimiters: [['[​[​', '​]​]']],\n\
    /// #         preview: \"[[maths]]\"\n\
    /// #       },\n\
    /// #       AsciiMath: {\n\
    /// #         decimal: \".\"\n\
    /// #       },\n\
    /// #       \"HTML-CSS\": {\n\
    /// #         undefinedFamily: \"STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif\"\n\
    /// #       }\n\
    /// #     });\n\
    /// # ".as_bytes()).unwrap();
    /// # /*
    /// let root: PathBuf = /* obtained elsewhere */;
    /// # */
    ///
    /// let lit_p = ScriptElement::from_file(&("$ROOT/MathJax-config.js".to_string(), root.join("MathJax-config.js"))).unwrap();
    /// assert_eq!(format!("{}{}{}", lit_p.head(), lit_p.content(), lit_p.foot()),
    /// "<script type=\"text/javascript\">\n\n\
    ///     MathJax.Hub.Config({\n\
    ///       jax: [\"input/AsciiMath\", \"output/HTML-CSS\"],\n\
    ///       extensions: [\"asciimath2jax.js\"],\n\
    ///       asciimath2jax: {\n\
    ///         delimiters: [['[​[​', '​]​]']],\n\
    ///         preview: \"[[maths]]\"\n\
    ///       },\n\
    ///       AsciiMath: {\n\
    ///         decimal: \".\"\n\
    ///       },\n\
    ///       \"HTML-CSS\": {\n\
    ///         undefinedFamily: \"STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif\"\n\
    ///       }\n\
    ///     });\n\
    /// \n\n</script>\n");
    /// ```
    pub fn from_file(path: &(String, PathBuf)) -> Result<ScriptElement, Error> {
        Ok(ScriptElement {
            class: ElementClass::Literal,
            data: read_file(path, "literal script element from path")?.into(),
        })
    }

    /// Read data from the filesystem, if appropriate.
    ///
    /// Path elements are concatenated with the specified root, then [`read_file()`](../util/fn.read_file.html)d in, becoming
    /// literals.
    ///
    /// Non-path elements are unaffected.
    ///
    /// # Examples
    ///
    /// Given the following directory layout:
    ///
    /// ```plaintext
    /// $ROOT
    ///   MathJax-config.js
    ///   assets
    ///     octicons.js
    /// ```
    ///
    /// Given `$ROOT/MathJax-config.js` containing:
    ///
    /// ```js
    /// MathJax.Hub.Config({
    ///   jax: ["input/AsciiMath", "output/HTML-CSS"],
    ///   extensions: ["asciimath2jax.js"],
    ///   asciimath2jax: {
    ///     delimiters: [['[​[​', '​]​]']],
    ///     preview: "[[maths]]"
    ///   },
    ///   AsciiMath: {
    ///     decimal: "."
    ///   },
    ///   "HTML-CSS": {
    ///     undefinedFamily: "STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif"
    ///   }
    /// });
    /// ```
    ///
    /// Given `$ROOT/assets/octicons.js` containing:
    ///
    /// ```js
    /// window.addEventListener("load", function() {
    ///     const PLACEHOLDER = document.getElementById("octicons-placeholder");
    ///
    ///     const request = new XMLHttpRequest();
    ///     request.open("GET", "/content/assets/octicons/sprite.octicons.svg");
    ///     request.onload = function(load) {
    ///         PLACEHOLDER.outerHTML = load.target.responseText.replace("<svg", "<svg class=\"hidden\"");
    ///     };
    ///     request.send();
    /// });
    /// ```
    ///
    /// The following holds:
    ///
    /// ```
    /// # use bloguen::ops::ScriptElement;
    /// # use std::fs::{self, File};
    /// # use std::env::temp_dir;
    /// # use std::io::Write;
    /// # use bloguen::Error;
    /// # let root = temp_dir().join("bloguen-doctest").join("ops-output-wrapped_element-script_element-load");
    /// # fs::create_dir_all(root.join("assets")).unwrap();
    /// # File::create(root.join("MathJax-config.js")).unwrap().write_all("\
    /// #     MathJax.Hub.Config({\n\
    /// #       jax: [\"input/AsciiMath\", \"output/HTML-CSS\"],\n\
    /// #       extensions: [\"asciimath2jax.js\"],\n\
    /// #       asciimath2jax: {\n\
    /// #         delimiters: [['[​[​', '​]​]']],\n\
    /// #         preview: \"[[maths]]\"\n\
    /// #       },\n\
    /// #       AsciiMath: {\n\
    /// #         decimal: \".\"\n\
    /// #       },\n\
    /// #       \"HTML-CSS\": {\n\
    /// #         undefinedFamily: \"STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif\"\n\
    /// #       }\n\
    /// #     });\n\
    /// # ".as_bytes()).unwrap();
    /// # File::create(root.join("assets").join("octicons.js")).unwrap().write_all("window.addEventListener(\"load\", function() {\n\
    /// #     const PLACEHOLDER = document.getElementById(\"octicons-placeholder\");\n\
    /// #     \n\
    /// #     const request = new XMLHttpRequest();\n\
    /// #     request.open(\"GET\", \"/content/assets/octicons/sprite.octicons.svg\");\n\
    /// #     request.onload = function(load) {\n\
    /// #         PLACEHOLDER.outerHTML = load.target.responseText.replace(\"<svg\", \"<svg class=\\\"hidden\\\"\");\n\
    /// #     };\n\
    /// #     request.send();\n\
    /// # });\n\
    /// # ".as_bytes()).unwrap();
    /// # /*
    /// let root: PathBuf = /* obtained elsewhere */;
    /// # */
    ///
    /// let mut elem = ScriptElement::from_path("MathJax-config.js");
    /// assert_eq!(elem.load(&("$ROOT".to_string(), root.clone())), Ok(()));
    /// assert_eq!(elem, ScriptElement::from_literal("\
    ///     MathJax.Hub.Config({\n\
    ///       jax: [\"input/AsciiMath\", \"output/HTML-CSS\"],\n\
    ///       extensions: [\"asciimath2jax.js\"],\n\
    ///       asciimath2jax: {\n\
    ///         delimiters: [['[​[​', '​]​]']],\n\
    ///         preview: \"[[maths]]\"\n\
    ///       },\n\
    ///       AsciiMath: {\n\
    ///         decimal: \".\"\n\
    ///       },\n\
    ///       \"HTML-CSS\": {\n\
    ///         undefinedFamily: \"STIXGeneral,'DejaVu Sans Mono','Arial Unicode MS',serif\"\n\
    ///       }\n\
    ///     });\n\
    /// "));
    ///
    /// let mut elem = ScriptElement::from_path("assets/.././assets/octicons.js");
    /// assert_eq!(elem.load(&("$ROOT".to_string(), root.clone())), Ok(()));
    /// assert_eq!(elem, ScriptElement::from_literal("\
    /// window.addEventListener(\"load\", function() {\n\
    ///     const PLACEHOLDER = document.getElementById(\"octicons-placeholder\");\n\
    ///     \n\
    ///     const request = new XMLHttpRequest();\n\
    ///     request.open(\"GET\", \"/content/assets/octicons/sprite.octicons.svg\");\n\
    ///     request.onload = function(load) {\n\
    ///         PLACEHOLDER.outerHTML = load.target.responseText.replace(\"<svg\", \"<svg class=\\\"hidden\\\"\");\n\
    ///     };\n\
    ///     request.send();\n\
    /// });\n\
    /// "));
    ///
    /// let mut elem = ScriptElement::from_path("assets/nonexistant.js");
    /// assert_eq!(elem.load(&("$ROOT".to_string(), root.clone())), Err(Error::FileNotFound {
    ///     who: "file script element",
    ///     path: "$ROOT/assets/nonexistant.js".into(),
    /// }));
    /// assert_eq!(elem, ScriptElement::from_path("assets/nonexistant.js"));
    /// ```
    pub fn load(&mut self, base: &(String, PathBuf)) -> Result<(), Error> {
        if self.class == ElementClass::File {
            self.data = read_file(&(format!("{}{}{}",
                                            base.0,
                                            if !is_path_separator(base.0.as_bytes()[base.0.as_bytes().len() - 1] as char) &&
                                               !is_path_separator(self.data.as_bytes()[0] as char) {
                                                "/"
                                            } else {
                                                ""
                                            },
                                            self.data),
                                    concat_path(base.1.clone(), &self.data)),
                                  "file script element")
                ?
                .into();
            self.class = ElementClass::Literal;
        }

        Ok(())
    }
}

impl WrappedElement for ScriptElement {
    fn head(&self) -> &str {
        match self.class {
            ElementClass::Link => &SCRIPT_LINK_HEAD,
            ElementClass::Literal => &SCRIPT_LITERAL_HEAD,
            ElementClass::File => "&lt;",
        }
    }

    fn content(&self) -> &str {
        &self.data
    }

    fn foot(&self) -> &str {
        match self.class {
            ElementClass::Link => &SCRIPT_LINK_FOOT,
            ElementClass::Literal => &SCRIPT_LITERAL_FOOT,
            ElementClass::File => "&gt;\n",
        }
    }
}


const SCRIPT_FIELDS: &[&str] = &["class", "data"];

struct ScriptElementVisitor;

impl<'de> de::Visitor<'de> for ScriptElementVisitor {
    type Value = ScriptElement;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("struct ScriptElement")
    }

    fn visit_str<E: de::Error>(self, v: &str) -> Result<ScriptElement, E> {
        let mut itr = v.splitn(2, ":");
        Ok(match (itr.next(), itr.next()) {
            (Some(val), None) |
            (Some("literal"), Some(val)) => {
                ScriptElement {
                    class: ElementClass::Literal,
                    data: val.to_string().into(),
                }
            }
            (Some("link"), Some(val)) => {
                ScriptElement {
                    class: ElementClass::Link,
                    data: val.to_string().into(),
                }
            }
            (Some("file"), Some(val)) => {
                ScriptElement {
                    class: ElementClass::File,
                    data: val.to_string().into(),
                }
            }

            (Some(tp), Some(_)) => return Err(de::Error::invalid_value(de::Unexpected::Str(tp), &r#""literal", "link", or "file""#)),
            (None, ..) => unreachable!(),
        })
    }

    fn visit_map<V: de::MapAccess<'de>>(self, mut map: V) -> Result<ScriptElement, V::Error> {
        let mut class = None;
        let mut data = None;
        while let Some(key) = map.next_key()? {
            match key {
                "class" => {
                    if class.is_some() {
                        return Err(de::Error::duplicate_field("class"));
                    }
                    class = Some(match map.next_value()? {
                        "literal" => ElementClass::Literal,
                        "link" => ElementClass::Link,
                        "file" => ElementClass::File,
                        val => return Err(de::Error::invalid_value(de::Unexpected::Str(val), &r#""literal", "link", or "file""#)),
                    });
                }
                "data" => {
                    if data.is_some() {
                        return Err(de::Error::duplicate_field("data"));
                    }
                    data = Some(map.next_value()?);
                }
                _ => return Err(de::Error::unknown_field(key, SCRIPT_FIELDS)),
            }
        }

        Ok(ScriptElement {
            class: class.ok_or_else(|| de::Error::missing_field("class"))?,
            data: data.ok_or_else(|| de::Error::missing_field("data"))?,
        })
    }
}

impl<'de> de::Deserialize<'de> for ScriptElement {
    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_struct("ScriptElement", SCRIPT_FIELDS, ScriptElementVisitor)
    }
}


}