static-serve-macro 0.6.0

A helper for compressing and embedding static assets in an Axum webserver
Documentation
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! Proc macro crate for compressing and embedding static assets
//! in a web server

use std::{
    convert::Into,
    fs,
    io::{self, Write},
    path::{Path, PathBuf},
};

use display_full_error::DisplayFullError;
use flate2::write::GzEncoder;
use glob::glob;
use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, quote};
use sha2::{Digest as _, Sha256};
use syn::{
    Ident, LitBool, LitByteStr, LitStr, Token, bracketed,
    parse::{Parse, ParseStream},
    parse_macro_input,
};

mod error;
use error::{Error, GzipType, ZstdType};

#[proc_macro]
/// Embed and optionally compress static assets for a web server
///
/// ```compile_fail,hidden
/// # // The corresponding successful test is in static-serve/tests/tests.rs,
/// # // where tests usually belong. It's called serves_unknown_attributes.
/// # // But only doctests support the `compile_fail` attribute so the failing
/// # // test is placed here.
/// embed_assets!(
///     "../static-serve/test_unknown_extensions",
///     allow_unknown_extensions = false
/// );
/// ```
pub fn embed_assets(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let parsed = parse_macro_input!(input as EmbedAssets);
    quote! { #parsed }.into()
}

#[proc_macro]
/// Embed and optionally compress a single static asset for a web server
pub fn embed_asset(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let parsed = parse_macro_input!(input as EmbedAsset);
    quote! { #parsed }.into()
}

struct EmbedAsset {
    asset_file: AssetFile,
    should_compress: ShouldCompress,
    cache_busted: IsCacheBusted,
    allow_unknown_extensions: LitBool,
}

struct AssetFile(LitStr);

impl Parse for EmbedAsset {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let asset_file: AssetFile = input.parse()?;

        // Default to no compression, no cache-busting
        let mut maybe_should_compress = None;
        let mut maybe_is_cache_busted = None;
        let mut maybe_allow_unknown_extensions = None;

        while !input.is_empty() {
            input.parse::<Token![,]>()?;
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;

            match key.to_string().as_str() {
                "compress" => {
                    let value = input.parse()?;
                    maybe_should_compress = Some(value);
                }
                "cache_bust" => {
                    let value = input.parse()?;
                    maybe_is_cache_busted = Some(value);
                }
                "allow_unknown_extensions" => {
                    let value = input.parse()?;
                    maybe_allow_unknown_extensions = Some(value);
                }
                _ => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "Unknown key in `embed_asset!` macro. Expected `compress`, `cache_bust`, or `allow_unknown_extensions` but got {key}"
                        ),
                    ));
                }
            }
        }
        let should_compress = maybe_should_compress.unwrap_or_else(|| {
            ShouldCompress(LitBool {
                value: false,
                span: Span::call_site(),
            })
        });
        let cache_busted = maybe_is_cache_busted.unwrap_or_else(|| {
            IsCacheBusted(LitBool {
                value: false,
                span: Span::call_site(),
            })
        });
        let allow_unknown_extensions = maybe_allow_unknown_extensions.unwrap_or(LitBool {
            value: false,
            span: Span::call_site(),
        });

        Ok(Self {
            asset_file,
            should_compress,
            cache_busted,
            allow_unknown_extensions,
        })
    }
}

impl Parse for AssetFile {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let input_span = input.span();
        let asset_file: LitStr = input.parse()?;
        let literal = asset_file.value();
        let path = Path::new(&literal);
        let metadata = match fs::metadata(path) {
            Ok(meta) => meta,
            Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound) => {
                return Err(syn::Error::new(
                    input_span,
                    format!("The specified asset file ({literal}) does not exist."),
                ));
            }
            Err(e) => {
                return Err(syn::Error::new(
                    input_span,
                    format!("Error reading file {literal}: {}", DisplayFullError(&e)),
                ));
            }
        };

        if metadata.is_dir() {
            return Err(syn::Error::new(
                input_span,
                "The specified asset is a directory, not a file. Did you mean to call `embed_assets!` instead?",
            ));
        }

        Ok(AssetFile(asset_file))
    }
}

impl ToTokens for EmbedAsset {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let AssetFile(asset_file) = &self.asset_file;
        let ShouldCompress(should_compress) = &self.should_compress;
        let IsCacheBusted(cache_busted) = &self.cache_busted;
        let allow_unknown_extensions = &self.allow_unknown_extensions;

        let result = generate_static_handler(
            asset_file,
            should_compress,
            cache_busted,
            allow_unknown_extensions,
        );

        match result {
            Ok(value) => {
                tokens.extend(quote! {
                    #value
                });
            }
            Err(err_message) => {
                let error = syn::Error::new(Span::call_site(), err_message);
                tokens.extend(error.to_compile_error());
            }
        }
    }
}

struct EmbedAssets {
    assets_dir: AssetsDir,
    validated_ignore_paths: IgnorePaths,
    should_compress: ShouldCompress,
    should_strip_html_ext: ShouldStripHtmlExt,
    cache_busted_paths: CacheBustedPaths,
    allow_unknown_extensions: LitBool,
}

impl Parse for EmbedAssets {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let assets_dir: AssetsDir = input.parse()?;

        // Default to no compression
        let mut maybe_should_compress = None;
        let mut maybe_ignore_paths = None;
        let mut maybe_should_strip_html_ext = None;
        let mut maybe_cache_busted_paths = None;
        let mut maybe_allow_unknown_extensions = None;

        while !input.is_empty() {
            input.parse::<Token![,]>()?;
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;

            match key.to_string().as_str() {
                "compress" => {
                    let value = input.parse()?;
                    maybe_should_compress = Some(value);
                }
                "ignore_paths" => {
                    let value = input.parse()?;
                    maybe_ignore_paths = Some(value);
                }
                "strip_html_ext" => {
                    let value = input.parse()?;
                    maybe_should_strip_html_ext = Some(value);
                }
                "cache_busted_paths" => {
                    let value = input.parse()?;
                    maybe_cache_busted_paths = Some(value);
                }
                "allow_unknown_extensions" => {
                    let value = input.parse()?;
                    maybe_allow_unknown_extensions = Some(value);
                }
                _ => {
                    return Err(syn::Error::new(
                        key.span(),
                        "Unknown key in embed_assets! macro. Expected `compress`, `ignore_paths`, `strip_html_ext`, `cache_busted_paths`, or `allow_unknown_extensions`",
                    ));
                }
            }
        }

        let should_compress = maybe_should_compress.unwrap_or_else(|| {
            ShouldCompress(LitBool {
                value: false,
                span: Span::call_site(),
            })
        });

        let should_strip_html_ext = maybe_should_strip_html_ext.unwrap_or_else(|| {
            ShouldStripHtmlExt(LitBool {
                value: false,
                span: Span::call_site(),
            })
        });

        let ignore_paths_with_span = maybe_ignore_paths.unwrap_or(IgnorePathsWithSpan(vec![]));
        let validated_ignore_paths = validate_ignore_paths(ignore_paths_with_span, &assets_dir.0)?;

        let maybe_cache_busted_paths =
            maybe_cache_busted_paths.unwrap_or(CacheBustedPathsWithSpan(vec![]));
        let cache_busted_paths =
            validate_cache_busted_paths(maybe_cache_busted_paths, &assets_dir.0)?;

        let allow_unknown_extensions = maybe_allow_unknown_extensions.unwrap_or(LitBool {
            value: false,
            span: Span::call_site(),
        });

        Ok(Self {
            assets_dir,
            validated_ignore_paths,
            should_compress,
            should_strip_html_ext,
            cache_busted_paths,
            allow_unknown_extensions,
        })
    }
}

impl ToTokens for EmbedAssets {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let AssetsDir(assets_dir) = &self.assets_dir;
        let ignore_paths = &self.validated_ignore_paths;
        let ShouldCompress(should_compress) = &self.should_compress;
        let ShouldStripHtmlExt(should_strip_html_ext) = &self.should_strip_html_ext;
        let cache_busted_paths = &self.cache_busted_paths;
        let allow_unknown_extensions = &self.allow_unknown_extensions;

        let result = generate_static_routes(
            assets_dir,
            ignore_paths,
            should_compress,
            should_strip_html_ext,
            cache_busted_paths,
            allow_unknown_extensions.value,
        );

        match result {
            Ok(value) => {
                tokens.extend(quote! {
                    #value
                });
            }
            Err(err_message) => {
                let error = syn::Error::new(Span::call_site(), err_message);
                tokens.extend(error.to_compile_error());
            }
        }
    }
}

struct AssetsDir(LitStr);

impl Parse for AssetsDir {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let input_span = input.span();
        let assets_dir: LitStr = input.parse()?;
        let literal = assets_dir.value();
        let path = Path::new(&literal);
        let metadata = match fs::metadata(path) {
            Ok(meta) => meta,
            Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound) => {
                return Err(syn::Error::new(
                    input_span,
                    "The specified assets directory does not exist",
                ));
            }
            Err(e) => {
                return Err(syn::Error::new(
                    input_span,
                    format!(
                        "Error reading directory {literal}: {}",
                        DisplayFullError(&e)
                    ),
                ));
            }
        };

        if !metadata.is_dir() {
            return Err(syn::Error::new(
                input_span,
                "The specified assets directory is not a directory",
            ));
        }

        Ok(AssetsDir(assets_dir))
    }
}

struct IgnorePaths(Vec<PathBuf>);

struct IgnorePathsWithSpan(Vec<(PathBuf, Span)>);

impl Parse for IgnorePathsWithSpan {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let dirs = parse_dirs(input)?;

        Ok(IgnorePathsWithSpan(dirs))
    }
}

fn validate_ignore_paths(
    ignore_paths: IgnorePathsWithSpan,
    assets_dir: &LitStr,
) -> syn::Result<IgnorePaths> {
    let mut valid_ignore_paths = Vec::new();
    for (dir, span) in ignore_paths.0 {
        let full_path = PathBuf::from(assets_dir.value()).join(&dir);
        match fs::metadata(&full_path) {
            Ok(_) => valid_ignore_paths.push(full_path),
            Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound) => {
                return Err(syn::Error::new(
                    span,
                    "The specified ignored path does not exist",
                ));
            }
            Err(e) => {
                return Err(syn::Error::new(
                    span,
                    format!(
                        "Error reading ignored path {}: {}",
                        dir.to_string_lossy(),
                        DisplayFullError(&e)
                    ),
                ));
            }
        }
    }
    Ok(IgnorePaths(valid_ignore_paths))
}

struct ShouldCompress(LitBool);

impl Parse for ShouldCompress {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let lit = input.parse()?;
        Ok(ShouldCompress(lit))
    }
}

struct ShouldStripHtmlExt(LitBool);

impl Parse for ShouldStripHtmlExt {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let lit = input.parse()?;
        Ok(ShouldStripHtmlExt(lit))
    }
}

struct IsCacheBusted(LitBool);

impl Parse for IsCacheBusted {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let lit = input.parse()?;
        Ok(IsCacheBusted(lit))
    }
}

struct CacheBustedPaths {
    dirs: Vec<PathBuf>,
    files: Vec<PathBuf>,
}
struct CacheBustedPathsWithSpan(Vec<(PathBuf, Span)>);

impl Parse for CacheBustedPathsWithSpan {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let dirs = parse_dirs(input)?;
        Ok(CacheBustedPathsWithSpan(dirs))
    }
}

fn validate_cache_busted_paths(
    tuples: CacheBustedPathsWithSpan,
    assets_dir: &LitStr,
) -> syn::Result<CacheBustedPaths> {
    let mut valid_dirs = Vec::new();
    let mut valid_files = Vec::new();
    for (dir, span) in tuples.0 {
        let full_path = PathBuf::from(assets_dir.value()).join(&dir);
        match fs::metadata(&full_path) {
            Ok(meta) => {
                if meta.is_dir() {
                    valid_dirs.push(full_path);
                } else {
                    valid_files.push(full_path);
                }
            }
            Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound) => {
                return Err(syn::Error::new(
                    span,
                    "The specified directory for cache busting does not exist",
                ));
            }
            Err(e) => {
                return Err(syn::Error::new(
                    span,
                    format!(
                        "Error reading path {}: {}",
                        dir.to_string_lossy(),
                        DisplayFullError(&e)
                    ),
                ));
            }
        }
    }
    Ok(CacheBustedPaths {
        dirs: valid_dirs,
        files: valid_files,
    })
}

/// Helper function for turning an array of strs representing paths into
/// a `Vec` containing tuples of each `PathBuf` and its `Span` in the `ParseStream`
fn parse_dirs(input: ParseStream) -> syn::Result<Vec<(PathBuf, Span)>> {
    let inner_content;
    bracketed!(inner_content in input);

    let mut dirs = Vec::new();
    while !inner_content.is_empty() {
        let directory_span = inner_content.span();
        let directory_str = inner_content.parse::<LitStr>()?;
        let path = PathBuf::from(directory_str.value());
        dirs.push((path, directory_span));

        if !inner_content.is_empty() {
            inner_content.parse::<Token![,]>()?;
        }
    }
    Ok(dirs)
}

fn generate_static_routes(
    assets_dir: &LitStr,
    ignore_paths: &IgnorePaths,
    should_compress: &LitBool,
    should_strip_html_ext: &LitBool,
    cache_busted_paths: &CacheBustedPaths,
    allow_unknown_extensions: bool,
) -> Result<TokenStream, error::Error> {
    let assets_dir_abs = Path::new(&assets_dir.value())
        .canonicalize()
        .map_err(Error::CannotCanonicalizeDirectory)?;
    let assets_dir_abs_str = assets_dir_abs
        .to_str()
        .ok_or(Error::InvalidUnicodeInDirectoryName)?;
    let canon_ignore_paths = ignore_paths
        .0
        .iter()
        .map(|d| {
            d.canonicalize()
                .map_err(Error::CannotCanonicalizeIgnorePath)
        })
        .collect::<Result<Vec<_>, _>>()?;
    let canon_cache_busted_dirs = cache_busted_paths
        .dirs
        .iter()
        .map(|d| {
            d.canonicalize()
                .map_err(Error::CannotCanonicalizeCacheBustedDir)
        })
        .collect::<Result<Vec<_>, _>>()?;
    let canon_cache_busted_files = cache_busted_paths
        .files
        .iter()
        .map(|file| file.canonicalize().map_err(Error::CannotCanonicalizeFile))
        .collect::<Result<Vec<_>, _>>()?;

    let mut routes = Vec::new();
    for entry in glob(&format!("{assets_dir_abs_str}/**/*")).map_err(Error::Pattern)? {
        let entry = entry.map_err(Error::Glob)?;
        let metadata = entry.metadata().map_err(Error::CannotGetMetadata)?;
        if metadata.is_dir() {
            continue;
        }

        // Skip `entry`s which are located in ignored paths
        if canon_ignore_paths
            .iter()
            .any(|ignore_path| entry.starts_with(ignore_path))
        {
            continue;
        }

        let mut is_entry_cache_busted = false;
        if canon_cache_busted_dirs
            .iter()
            .any(|dir| entry.starts_with(dir))
            || canon_cache_busted_files.contains(&entry)
        {
            is_entry_cache_busted = true;
        }

        let entry = entry
            .canonicalize()
            .map_err(Error::CannotCanonicalizeFile)?;
        let entry_str = entry.to_str().ok_or(Error::FilePathIsNotUtf8)?;
        let EmbeddedFileInfo {
            entry_path,
            content_type,
            etag_str,
            lit_byte_str_contents,
            maybe_gzip,
            maybe_zstd,
            cache_busted,
        } = EmbeddedFileInfo::from_path(
            &entry,
            Some(assets_dir_abs_str),
            should_compress,
            should_strip_html_ext,
            is_entry_cache_busted,
            allow_unknown_extensions,
        )?;

        routes.push(quote! {
            router = ::static_serve::static_route(
                router,
                #entry_path,
                #content_type,
                #etag_str,
                {
                    // Poor man's `tracked_path`
                    // https://github.com/rust-lang/rust/issues/99515
                    const _: &[u8] = include_bytes!(#entry_str);
                        #lit_byte_str_contents
                },
                #maybe_gzip,
                #maybe_zstd,
                #cache_busted
            );
        });
    }

    Ok(quote! {
    pub fn static_router<S>() -> ::axum::Router<S>
        where S: ::std::clone::Clone + ::std::marker::Send + ::std::marker::Sync + 'static {
            let mut router = ::axum::Router::<S>::new();
            #(#routes)*
            router
        }
    })
}

fn generate_static_handler(
    asset_file: &LitStr,
    should_compress: &LitBool,
    cache_busted: &LitBool,
    allow_unknown_extensions: &LitBool,
) -> Result<TokenStream, error::Error> {
    let asset_file_abs = Path::new(&asset_file.value())
        .canonicalize()
        .map_err(Error::CannotCanonicalizeFile)?;
    let asset_file_abs_str = asset_file_abs.to_str().ok_or(Error::FilePathIsNotUtf8)?;

    let EmbeddedFileInfo {
        entry_path: _,
        content_type,
        etag_str,
        lit_byte_str_contents,
        maybe_gzip,
        maybe_zstd,
        cache_busted,
    } = EmbeddedFileInfo::from_path(
        &asset_file_abs,
        None,
        should_compress,
        &LitBool {
            value: false,
            span: Span::call_site(),
        },
        cache_busted.value(),
        allow_unknown_extensions.value(),
    )?;

    let route = quote! {
        ::static_serve::static_method_router(
            #content_type,
            #etag_str,
            {
                // Poor man's `tracked_path`
                // https://github.com/rust-lang/rust/issues/99515
                const _: &[u8] = include_bytes!(#asset_file_abs_str);
                #lit_byte_str_contents
            },
            #maybe_gzip,
            #maybe_zstd,
            #cache_busted
        )
    };

    Ok(route)
}

struct OptionBytesSlice(Option<LitByteStr>);
impl ToTokens for OptionBytesSlice {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.extend(if let Some(inner) = &self.0.as_ref() {
            quote! { ::std::option::Option::Some(#inner) }
        } else {
            quote! { ::std::option::Option::None }
        });
    }
}

struct EmbeddedFileInfo {
    /// When creating a `Router`, we need the API path/route to the
    /// target file. If creating a `Handler`, this is not needed since
    /// the router is responsible for the file's path on the server.
    entry_path: Option<String>,
    content_type: String,
    etag_str: String,
    lit_byte_str_contents: LitByteStr,
    maybe_gzip: OptionBytesSlice,
    maybe_zstd: OptionBytesSlice,
    cache_busted: bool,
}

impl EmbeddedFileInfo {
    fn from_path(
        pathbuf: &PathBuf,
        assets_dir_abs_str: Option<&str>,
        should_compress: &LitBool,
        should_strip_html_ext: &LitBool,
        cache_busted: bool,
        allow_unknown_extensions: bool,
    ) -> Result<Self, Error> {
        let contents = fs::read(pathbuf).map_err(Error::CannotReadEntryContents)?;

        // Optionally compress files
        let (maybe_gzip, maybe_zstd) = if should_compress.value {
            let gzip = gzip_compress(&contents)?;
            let zstd = zstd_compress(&contents)?;
            (gzip, zstd)
        } else {
            (None, None)
        };

        let content_type = file_content_type(pathbuf, allow_unknown_extensions)?;

        // entry_path is only needed for the router (embed_assets!)
        let entry_path = if let Some(dir) = assets_dir_abs_str {
            let relative_entry = pathbuf
                .strip_prefix(dir)
                .ok()
                .and_then(|p| p.to_str())
                .ok_or(Error::InvalidUnicodeInEntryName)?;
            let mut web_path = normalize_web_path(relative_entry);
            if should_strip_html_ext.value && content_type == "text/html" {
                strip_html_ext(&mut web_path);
            }

            Some(web_path)
        } else {
            None
        };

        let etag_str = etag(&contents);
        let lit_byte_str_contents = LitByteStr::new(&contents, Span::call_site());
        let maybe_gzip = OptionBytesSlice(maybe_gzip);
        let maybe_zstd = OptionBytesSlice(maybe_zstd);

        Ok(Self {
            entry_path,
            content_type,
            etag_str,
            lit_byte_str_contents,
            maybe_gzip,
            maybe_zstd,
            cache_busted,
        })
    }
}

fn gzip_compress(contents: &[u8]) -> Result<Option<LitByteStr>, Error> {
    let mut compressor = GzEncoder::new(Vec::new(), flate2::Compression::best());
    compressor
        .write_all(contents)
        .map_err(|e| Error::Gzip(GzipType::CompressorWrite(e)))?;
    let compressed = compressor
        .finish()
        .map_err(|e| Error::Gzip(GzipType::EncoderFinish(e)))?;

    Ok(maybe_get_compressed(&compressed, contents))
}

fn zstd_compress(contents: &[u8]) -> Result<Option<LitByteStr>, Error> {
    let level = *zstd::compression_level_range().end();
    let mut encoder = zstd::Encoder::new(Vec::new(), level).unwrap();
    write_to_zstd_encoder(&mut encoder, contents)
        .map_err(|e| Error::Zstd(ZstdType::EncoderWrite(e)))?;

    let compressed = encoder
        .finish()
        .map_err(|e| Error::Zstd(ZstdType::EncoderFinish(e)))?;

    Ok(maybe_get_compressed(&compressed, contents))
}

fn write_to_zstd_encoder(
    encoder: &mut zstd::Encoder<'static, Vec<u8>>,
    contents: &[u8],
) -> io::Result<()> {
    encoder.set_pledged_src_size(Some(
        contents
            .len()
            .try_into()
            .expect("contents size should fit into u64"),
    ))?;
    encoder.window_log(23)?;
    encoder.include_checksum(false)?;
    encoder.include_contentsize(false)?;
    encoder.long_distance_matching(false)?;
    encoder.write_all(contents)?;

    Ok(())
}

fn is_compression_significant(compressed_len: usize, contents_len: usize) -> bool {
    let ninety_pct_original = contents_len / 10 * 9;
    compressed_len < ninety_pct_original
}

fn maybe_get_compressed(compressed: &[u8], contents: &[u8]) -> Option<LitByteStr> {
    is_compression_significant(compressed.len(), contents.len())
        .then(|| LitByteStr::new(compressed, Span::call_site()))
}

/// Use `mime_guess` to get the best guess of the file's MIME type
/// by looking at its extension, or return an error if unable.
///
/// If the `allow_unknown_extensions` parameter is true, an unknown ext
/// will not produce an error, but application/octet-stream.
///
/// We accept the first guess because [`mime_guess` updates the order
/// according to the latest IETF RTC](https://docs.rs/mime_guess/2.0.5/mime_guess/struct.MimeGuess.html#note-ordering)
fn file_content_type(path: &Path, allow_unknown_extensions: bool) -> Result<String, error::Error> {
    let ext = path.extension().ok_or(if allow_unknown_extensions {
        return Ok(mime_guess::mime::APPLICATION_OCTET_STREAM.to_string());
    } else {
        error::Error::UnknownFileExtension(None)
    })?;

    let ext = ext
        .to_str()
        .ok_or(error::Error::InvalidFileExtension(path.into()))?;

    let guess = mime_guess::MimeGuess::from_ext(ext);

    if allow_unknown_extensions {
        return Ok(guess.first_or_octet_stream().to_string());
    }

    guess
        .first_raw()
        .map(ToOwned::to_owned)
        .ok_or(error::Error::UnknownFileExtension(Some(ext.into())))
}

fn etag(contents: &[u8]) -> String {
    let sha256 = Sha256::digest(contents);
    let hash = u64::from_le_bytes(sha256[..8].try_into().unwrap())
        ^ u64::from_le_bytes(sha256[8..16].try_into().unwrap())
        ^ u64::from_le_bytes(sha256[16..24].try_into().unwrap())
        ^ u64::from_le_bytes(sha256[24..32].try_into().unwrap());
    format!("\"{hash:016x}\"")
}

/// Convert a relative filesystem-style path into a rooted web route.
///
/// Path segments are normalized via [`Path::components`] so separator
/// style differences across platforms do not affect route generation.
/// The returned route is always absolute (starts with `/`).
fn normalize_web_path(relative_path: &str) -> String {
    let normalized = Path::new(relative_path)
        .components()
        .filter_map(|component| match component {
            std::path::Component::Normal(segment) => segment.to_str(),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("/");
    format!("/{normalized}")
}

/// Strip `.html`/`.htm` from an already-normalized web path in-place,
/// and map `/index` to its parent directory route.
fn strip_html_ext(path: &mut String) {
    let ext = path.rsplit_once('.').map(|(_, ext)| ext);
    if ext.is_some_and(|ext| ext.eq_ignore_ascii_case("html")) {
        path.truncate(path.len() - ".html".len());
    } else if ext.is_some_and(|ext| ext.eq_ignore_ascii_case("htm")) {
        path.truncate(path.len() - ".htm".len());
    }

    if path.ends_with("/index") {
        path.truncate(path.len() - "index".len());
    } else if path == "/index" {
        path.truncate(1);
    }
}