fix(cli/devserver): inject autoreload into HTML only, closes #6997 (#7032)

This commit is contained in:
Amr Bashir
2023-05-23 17:39:11 +03:00
committed by GitHub
parent baa581b814
commit 3cb7a3e642
4 changed files with 27 additions and 5 deletions

View File

@@ -0,0 +1,6 @@
---
'tauri-cli': 'patch'
'@tauri-apps/cli': 'patch'
---
Fix built-in devserver adding hot-reload code to non-html files.

5
.changes/mime-type.md Normal file
View File

@@ -0,0 +1,5 @@
---
'tauri-utils': 'patch'
---
Add `MimeType::parse_with_fallback` and `MimeType::parse_from_uri_with_fallback`

View File

@@ -46,6 +46,11 @@ impl std::fmt::Display for MimeType {
impl MimeType {
/// parse a URI suffix to convert text/plain mimeType to their actual web compatible mimeType.
pub fn parse_from_uri(uri: &str) -> MimeType {
Self::parse_from_uri_with_fallback(uri, Self::Html)
}
/// parse a URI suffix to convert text/plain mimeType to their actual web compatible mimeType with specified fallback for unknown file extensions.
pub fn parse_from_uri_with_fallback(uri: &str, fallback: MimeType) -> MimeType {
let suffix = uri.split('.').last();
match suffix {
Some("bin") => Self::OctetStream,
@@ -61,15 +66,19 @@ impl MimeType {
Some("svg") => Self::Svg,
Some("mp4") => Self::Mp4,
// Assume HTML when a TLD is found for eg. `wry:://tauri.app` | `wry://hello.com`
Some(_) => Self::Html,
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
Some(_) => fallback,
// using octet stream according to this:
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
None => Self::OctetStream,
}
}
/// infer mimetype from content (or) URI if needed.
pub fn parse(content: &[u8], uri: &str) -> String {
Self::parse_with_fallback(content, uri, Self::Html)
}
/// infer mimetype from content (or) URI if needed with specified fallback for unknown file extensions.
pub fn parse_with_fallback(content: &[u8], uri: &str, fallback: MimeType) -> String {
let mime = if uri.ends_with(".svg") {
// when reading svg, we can't use `infer`
None
@@ -78,8 +87,10 @@ impl MimeType {
};
match mime {
Some(mime) if mime == MIMETYPE_PLAIN => Self::parse_from_uri(uri).to_string(),
None => Self::parse_from_uri(uri).to_string(),
Some(mime) if mime == MIMETYPE_PLAIN => {
Self::parse_from_uri_with_fallback(uri, fallback).to_string()
}
None => Self::parse_from_uri_with_fallback(uri, fallback).to_string(),
Some(mime) => mime.to_string(),
}
}

View File

@@ -145,7 +145,7 @@ async fn handler<T>(req: Request<T>, state: Arc<State>) -> impl IntoResponse {
file
.map(|mut f| {
let mime_type = MimeType::parse(&f, uri);
let mime_type = MimeType::parse_with_fallback(&f, uri, MimeType::OctetStream);
if mime_type == MimeType::Html.to_string() {
let mut document = kuchiki::parse_html().one(String::from_utf8_lossy(&f).into_owned());
fn with_html_head<F: FnOnce(&NodeRef)>(document: &mut NodeRef, f: F) {