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
#[macro_use]
extern crate html5ever;

use std::{
  collections::HashMap,
  fs,
  path::{Path, PathBuf},
};

use html5ever::QualName;
use kuchiki::traits::TendrilSink;
use kuchiki::NodeRef;
use once_cell::sync::Lazy;
use url::Url;

mod binary;
mod js_css;

static FONT_EXTENSIONS: &[&str] = &[".eot", ".woff2", ".woff", ".tff"];
const SPACE_REPLACEMENT: &str = "~~tauri-inliner-space~~";
const EOL_REPLACEMENT: &str = "~~tauri-inliner-eol~~";

/// Inliner error types.
#[derive(Debug, thiserror::Error)]
pub enum Error {
  /// A std::io::ErrorKind::NotFound error with the offending line in the string parameter
  #[error("`{0}`")]
  InvalidPath(String),
  /// Any other file read error that is not NotFound
  #[error("`{0}`")]
  Io(#[from] std::io::Error),
  #[error("http request error: `{0}`")]
  HttpRequest(#[from] reqwest::Error),
}

pub type Result<T> = std::result::Result<T, Error>;

/// Config struct that is passed to `inline_file()` and `inline_html_string()`
///
/// Default enables everything
#[derive(Debug, Copy, Clone)]
pub struct Config {
  /// Whether or not to inline fonts in the css as base64.
  pub inline_fonts: bool,
  /// Replace EOL's with a space character. Useful to keep line numbers the same in the output to help with debugging.
  pub remove_new_lines: bool,
  /// Whether to inline remote content or not.
  pub inline_remote: bool,
}

impl Default for Config {
  /// Enables everything
  fn default() -> Config {
    Config {
      inline_fonts: true,
      remove_new_lines: true,
      inline_remote: true,
    }
  }
}

fn content_type_map() -> &'static serde_json::Value {
  static MAP: Lazy<serde_json::Value> =
    Lazy::new(|| serde_json::from_str(include_str!("./content-type.json")).unwrap());
  &MAP
}

fn load_path<P: AsRef<Path>>(path: &str, config: &Config, root_path: P) -> Result<Option<String>> {
  if !config.inline_fonts && FONT_EXTENSIONS.iter().any(|f| path.ends_with(f)) {
    log::debug!(
      "[INLINER] `{}` is a font and config.inline_fonts == false",
      path
    );
    return Ok(None);
  }

  let raw = if let Ok(url) = Url::parse(path) {
    if config.inline_remote {
      let response = reqwest::blocking::Client::builder()
        .build()?
        .get(url)
        .send()?;
      if let Some(content_type) = response.headers().get(reqwest::header::CONTENT_TYPE) {
        let content_type = content_type.to_str().unwrap();
        if let Some(extension) = path.split('.').last() {
          let expected_content_type = content_type_map()
            .get(extension)
            .map(|c| c.to_string())
            .unwrap_or_else(|| content_type.to_string());
          if content_type != expected_content_type {
            log::debug!(
              "[INLINER] `{}` response's content type is invalid; expected {} but got {}",
              path,
              expected_content_type,
              content_type,
            );
            return Ok(None);
          }
        }
      }
      Some(response.bytes()?.as_ref().to_vec())
    } else {
      log::debug!(
        "[INLINER] `{}` is a remote URL and config.inline_remote == false",
        path
      );
      None
    }
  } else {
    let file_path = PathBuf::from(path);
    let file_path = if file_path.is_absolute() {
      file_path
    } else {
      root_path.as_ref().to_path_buf().join(file_path)
    };
    log::debug!(
      "[INLINER] loading `{:?}` with fs::read `{:?}`",
      file_path,
      path
    );
    fs::read(file_path).map(|file| Some(file.to_vec()))?
  };
  let res = if let Some(raw) = raw {
    Some(match path.split('.').last() {
      Some(extension) => {
        if let Some(content_type) = content_type_map().get(extension) {
          log::debug!(
            "[INLINER] encoding `{}` as base64 with content type `{}`",
            path,
            content_type.as_str().unwrap()
          );
          format!(
            "data:{};base64,{}",
            content_type.as_str().unwrap(),
            base64::encode(&raw)
          )
        } else {
          String::from_utf8_lossy(&raw).to_string()
        }
      }
      None => String::from_utf8_lossy(&raw).to_string(),
    })
  } else {
    None
  };
  Ok(res)
}

pub(crate) fn get<P: AsRef<Path>>(
  cache: &mut HashMap<String, Option<String>>,
  path: &str,
  config: &Config,
  root_path: P,
) -> Result<Option<String>> {
  log::debug!("[INLINER] loading {}", path);
  let query_replacer = regex::Regex::new(r"\??#.*").unwrap();
  let path = query_replacer.replace_all(path, "").to_string();
  if path.starts_with("data:") {
    return Ok(None);
  }

  if let Some(res) = cache.get(&path) {
    log::debug!("[INLINER] hit cache on {}", path);
    Ok(res.clone())
  } else {
    match load_path(&path, config, root_path) {
      Ok(res) => {
        cache.insert(path, res.clone());
        Ok(res)
      }
      Err(e) => {
        log::error!("error loading {}: {:?}", path, e);
        Ok(None)
      }
    }
  }
}

/// Returns a `Result<String>` of the html file at file path with all the assets inlined.
///
/// ## Arguments
/// * `file_path` - The path of the html file.
/// * `config` - Pass a config file to select what features to enable. Use `Default::default()` to enable everything
pub fn inline_file<P: AsRef<Path>>(file_path: P, config: Config) -> Result<String> {
  let html = fs::read_to_string(&file_path)?;
  inline_html_string(&html, &file_path.as_ref().parent().unwrap(), config)
}

/// Returns a `Result<String>` with all the assets linked in the the html string inlined.
///
/// ## Arguments
/// * `html` - The html string.
/// * `root_path` - The root all relative paths in the html will be evaluated with, usually this is the folder the html file is in.
/// * `config` - Pass a config file to select what features to enable. Use `Default::default()` to enable everything
///
pub fn inline_html_string<P: AsRef<Path>>(
  html: &str,
  root_path: P,
  config: Config,
) -> Result<String> {
  let mut cache = HashMap::new();
  let root_path = root_path.as_ref().canonicalize().unwrap();
  let document = kuchiki::parse_html().one(html);

  binary::inline_base64(&mut cache, &config, &root_path, &document)?;
  js_css::inline_script_link(&mut cache, &config, &root_path, &document)?;

  let html = if config.remove_new_lines {
    for target in document.select("pre, textarea, script").unwrap() {
      let node = target.as_node();
      let element = node.as_element().unwrap();
      let replacement_node = NodeRef::new_element(
        QualName::new(None, ns!(html), element.name.local.to_string().into()),
        None,
      );
      replacement_node.append(NodeRef::new_text(
        node
          .text_contents()
          .replace("\n", EOL_REPLACEMENT)
          .replace(" ", SPACE_REPLACEMENT),
      ));

      node.insert_after(replacement_node);
      node.detach();
    }
    let html = document.to_string();
    html
      .replace("\n", " ")
      .replace("\r", "")
      .replace(EOL_REPLACEMENT, "\n")
      .replace(SPACE_REPLACEMENT, " ")
  } else {
    document.to_string()
  };
  let whitespace_regex = regex::Regex::new(r"( {2,})").unwrap();
  let html = whitespace_regex.replace_all(&html, " ").to_string();

  Ok(html)
}

#[cfg(test)]
mod tests {
  use dissimilar::{diff, Chunk};
  use std::{
    fs::{read, read_to_string},
    io::Write,
    path::PathBuf,
    thread::spawn,
  };
  use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
  use tiny_http::{Header, Response, Server, StatusCode};

  #[cfg(windows)]
  const LINE_ENDING: &str = "\r\n";
  #[cfg(not(windows))]
  const LINE_ENDING: &str = "\n";

  #[test]
  fn match_fixture() {
    env_logger::init();

    let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let fixtures_path = root.join("src/fixtures");

    spawn(move || {
      let server = Server::http("localhost:54321").unwrap();
      for request in server.incoming_requests() {
        let requested = percent_encoding::percent_decode_str(request.url())
          .decode_utf8_lossy()
          .to_string();
        let url: PathBuf = requested.chars().skip(1).collect::<String>().into();
        let file_path = fixtures_path.join(url);
        if let Ok(contents) = read(&file_path) {
          let mut response = Response::from_data(contents);
          let content_type = super::content_type_map()
            .get(file_path.extension().unwrap().to_str().unwrap())
            .map(|c| c.to_string())
            .unwrap_or_else(|| "application/octet-stream".to_string());
          response.add_header(
            Header::from_bytes(&b"Content-Type"[..], &content_type.as_bytes()[..]).unwrap(),
          );
          request.respond(response).unwrap();
        } else {
          request
            .respond(Response::empty(StatusCode::from(404)))
            .unwrap();
        }
      }
    });

    for file in std::fs::read_dir(root.join(PathBuf::from("src/fixtures"))).unwrap() {
      let path = file.unwrap().path();
      let file_name = path.file_name().unwrap().to_str().unwrap();
      if !file_name.ends_with(".src.html") {
        continue;
      }

      let output = super::inline_file(&path, Default::default())
        .unwrap()
        .replace("\n", LINE_ENDING);

      let expected = read_to_string(
        path
          .parent()
          .unwrap()
          .join(file_name.replace(".src.html", ".result.html")),
      )
      .unwrap();

      if output != expected {
        _print_diff(output, expected);
        panic!("test case `{}` failed", file_name.replace(".src.html", ""));
      }
    }
  }

  fn _print_diff(text1: String, text2: String) {
    let difference = diff(&text1, &text2);

    let mut stdout = StandardStream::stdout(ColorChoice::Always);

    for i in 0..difference.len() {
      match difference[i] {
        Chunk::Equal(x) => {
          stdout.reset().unwrap();
          writeln!(stdout, " {}", x).unwrap();
        }
        Chunk::Insert(x) => {
          match difference[i - 1] {
            Chunk::Delete(ref y) => {
              stdout
                .set_color(ColorSpec::new().set_fg(Some(Color::Green)))
                .unwrap();
              write!(stdout, "+").unwrap();
              let diffs = diff(y, x);
              for c in diffs {
                match c {
                  Chunk::Equal(z) => {
                    stdout
                      .set_color(ColorSpec::new().set_fg(Some(Color::Green)))
                      .unwrap();
                    write!(stdout, "{}", z).unwrap();
                    write!(stdout, " ").unwrap();
                  }
                  Chunk::Insert(z) => {
                    stdout
                      .set_color(
                        ColorSpec::new()
                          .set_fg(Some(Color::White))
                          .set_bg(Some(Color::Green)),
                      )
                      .unwrap();
                    write!(stdout, "{}", z).unwrap();
                    stdout.reset().unwrap();
                    write!(stdout, " ").unwrap();
                  }
                  _ => (),
                }
              }
              writeln!(stdout).unwrap();
            }
            _ => {
              stdout
                .set_color(ColorSpec::new().set_fg(Some(Color::Green)))
                .unwrap();
              writeln!(stdout, "+{}", x).unwrap();
            }
          };
        }
        Chunk::Delete(x) => {
          stdout
            .set_color(ColorSpec::new().set_fg(Some(Color::Red)))
            .unwrap();
          writeln!(stdout, "-{}", x).unwrap();
        }
      }
    }
    stdout.reset().unwrap();
    stdout.flush().unwrap();
  }
}