hauchiwa 0.19.0

Flexible static website generator library with incremental rebuilds and cached image optimization
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
//! Utilities for working with output data and paths.
//!
//! This module contains the [`Output`] struct, which represents a final output file,
//! and helper functions for path normalization and slugification.

use camino::Utf8Component;
use camino::{Utf8Path, Utf8PathBuf};
use thiserror::Error;

use crate::Many;
use crate::One;
use crate::core::Dynamic;
use crate::engine::Handle;
use crate::engine::Map;
use crate::engine::TrackerPtr;

/// Helper function to compute the bundle scope path.
///
/// It returns the "folder" that owns this piece of content.
/// - content/foo/index.md -> content/foo
/// - content/foo/bar.md -> content/foo/bar
pub fn source_to_bundle(path: impl AsRef<Utf8Path>) -> Utf8PathBuf {
    let path = path.as_ref().with_extension("");

    // Check if the last component of the path is exactly "index.*"
    if let Some("index") = path.file_name() {
        // If it is, return its parent directory.
        // - "foo/index.html" -> parent is "foo"
        // - "/index.html"    -> parent is "/"
        // - "index.html"     -> parent is "" (empty path)
        if let Some(parent) = path.parent() {
            return parent.to_path_buf();
        }
    }

    // Otherwise, or if there's no parent (which is rare if file_name() matched),
    // return the original path converted to a Utf8PathBuf.
    path.to_path_buf()
}

/// Helper function to compute the web-accessible URL path (href).
///
/// It strips the source base and creates a pretty URL (ending in `/`).
pub fn source_to_href(path: &Utf8Path, base: Option<&str>) -> String {
    let path = if let Some(base) = base {
        path.strip_prefix(base).unwrap_or(path)
    } else {
        path
    };

    let mut url = String::from("/");

    // If it's not index.md, we need to append the stem (e.g., 'some-file')
    // If it IS index.md, we only want the parent directory structure.
    if let Some(parent) = path.parent() {
        url.push_str(parent.as_str());
    }

    let stem = path.file_stem().unwrap_or_default();
    if stem != "index" {
        if !url.ends_with('/') {
            url.push('/');
        }
        url.push_str(stem);
    }

    // Ensure trailing slash for directory-style routing
    if !url.ends_with('/') {
        url.push('/');
    }

    // Handling edge case: double slash at start if parent was empty
    if url.starts_with("//") {
        url[1..].to_string()
    } else {
        url
    }
}

/// Helper function to compute the dist path from the href.
///
/// It appends `index.html` to the href (relative to dist root).
pub fn href_to_dist(href: &str, dist_root: impl AsRef<Utf8Path>) -> Utf8PathBuf {
    // Remove leading slash to join correctly with dist_dir
    dist_root
        .as_ref()
        .join(href.trim_start_matches('/'))
        .join("index.html")
}

/// Normalize a path, removing things like `.` and `..`.
///
/// CAUTION: This does not resolve symlinks (unlike [`std::fs::canonicalize`]).
/// This may cause incorrect or surprising behavior at times. This should be
/// used carefully. Unfortunately, [`std::fs::canonicalize`] can be hard to use
/// correctly, since it can often fail, or on Windows returns annoying device
/// paths.
///
/// Adapted from
/// <https://github.com/rust-lang/cargo/blob/f7acf448fc127df9a77c52cc2bba027790ac4931/crates/cargo-util/src/paths.rs#L76-L116>
pub(crate) fn normalize_path(path: &Utf8Path) -> Utf8PathBuf {
    let mut components = path.components().peekable();
    let mut ret = if let Some(c @ Utf8Component::Prefix(..)) = components.peek().cloned() {
        components.next();
        Utf8PathBuf::from(c.as_str())
    } else {
        Utf8PathBuf::new()
    };

    for component in components {
        match component {
            Utf8Component::Prefix(..) => unreachable!(),
            Utf8Component::RootDir => {
                ret.push(Utf8Component::RootDir);
            }
            Utf8Component::CurDir => {}
            Utf8Component::ParentDir => {
                if ret.ends_with(Utf8Component::ParentDir) {
                    ret.push(Utf8Component::ParentDir);
                } else {
                    let popped = ret.pop();
                    if !popped && !ret.has_root() {
                        ret.push(Utf8Component::ParentDir);
                    }
                }
            }
            Utf8Component::Normal(c) => {
                ret.push(c);
            }
        }
    }
    ret
}

fn normalize_path_html(path: impl AsRef<Utf8Path>) -> Utf8PathBuf {
    let mut buffer = path.as_ref().to_path_buf();

    if let Some(file_name) = buffer.file_name() {
        if file_name == "index" || file_name.starts_with("index.") {
            buffer.set_extension("html");
        } else {
            buffer.set_extension("");
            buffer.push("index.html");
        }
    } else {
        buffer.push("index.html");
    }

    buffer
}

#[derive(Debug, Error)]
pub enum OutputPathError {
    /// The requested output path was not a safe path relative to `dist`.
    ///
    /// Output paths must stay inside the configured output directory. Absolute
    /// paths, parent-directory components (`..`), current-directory components
    /// (`.`), and empty file paths are rejected before an [`Output`] is created.
    #[error("Output path '{0}' is outside the configured dist directory")]
    UnsafePath(Utf8PathBuf),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OutputTargetKind {
    Page,
    File,
}

#[derive(Debug, Clone)]
/// A destination accepted by [`Output::to`].
///
/// Most users do not need to construct this type directly. Pass a route, file
/// path, [`crate::loader::generic::Document`], or
/// [`crate::loader::generic::DocumentMeta`] to [`Output::to`] instead.
pub struct OutputTarget {
    path: Utf8PathBuf,
    kind: OutputTargetKind,
}

impl OutputTarget {
    fn infer(path: impl Into<Utf8PathBuf>) -> Self {
        let path = path.into();
        let raw = path.as_str();
        let kind = if raw.is_empty()
            || raw.starts_with('/')
            || raw.ends_with('/')
            || path.extension().is_none()
        {
            OutputTargetKind::Page
        } else {
            OutputTargetKind::File
        };
        Self { path, kind }
    }

    fn page(route: impl Into<Utf8PathBuf>) -> Self {
        Self {
            path: route.into(),
            kind: OutputTargetKind::Page,
        }
    }

    fn file(path: impl Into<Utf8PathBuf>) -> Self {
        Self {
            path: path.into(),
            kind: OutputTargetKind::File,
        }
    }

    fn into_dist_path(self) -> Result<Utf8PathBuf, OutputPathError> {
        let path = match self.kind {
            OutputTargetKind::Page => route_to_page_path(&self.path),
            OutputTargetKind::File => self.path,
        };
        validate_output_path(path)
    }
}

/// Converts a value into an output destination for [`Output::to`].
///
/// Strings and paths are interpreted by convention: values that look like web
/// routes become pretty HTML pages, while values with a file extension become
/// exact file paths. Loaded documents use their generated `meta.href`, making
/// `Output::to(document).html(rendered)?` the shortest path from a document to
/// its rendered page.
pub trait IntoOutputTarget {
    fn into_output_target(self) -> OutputTarget;
}

impl IntoOutputTarget for OutputTarget {
    fn into_output_target(self) -> OutputTarget {
        self
    }
}

impl IntoOutputTarget for &str {
    fn into_output_target(self) -> OutputTarget {
        OutputTarget::infer(self)
    }
}

impl IntoOutputTarget for String {
    fn into_output_target(self) -> OutputTarget {
        OutputTarget::infer(self)
    }
}

impl IntoOutputTarget for &String {
    fn into_output_target(self) -> OutputTarget {
        OutputTarget::infer(self.as_str())
    }
}

impl IntoOutputTarget for Utf8PathBuf {
    fn into_output_target(self) -> OutputTarget {
        OutputTarget::infer(self)
    }
}

impl IntoOutputTarget for &Utf8Path {
    fn into_output_target(self) -> OutputTarget {
        OutputTarget::infer(self.to_path_buf())
    }
}

impl IntoOutputTarget for &Utf8PathBuf {
    fn into_output_target(self) -> OutputTarget {
        OutputTarget::infer(self.clone())
    }
}

impl<T> IntoOutputTarget for &crate::loader::generic::Document<T> {
    fn into_output_target(self) -> OutputTarget {
        OutputTarget::page(self.meta.href.as_str())
    }
}

impl<T> IntoOutputTarget for &&crate::loader::generic::Document<T> {
    fn into_output_target(self) -> OutputTarget {
        OutputTarget::page(self.meta.href.as_str())
    }
}

impl IntoOutputTarget for &crate::loader::generic::DocumentMeta {
    fn into_output_target(self) -> OutputTarget {
        OutputTarget::page(self.href.as_str())
    }
}

impl IntoOutputTarget for &&crate::loader::generic::DocumentMeta {
    fn into_output_target(self) -> OutputTarget {
        OutputTarget::page(self.href.as_str())
    }
}

fn route_to_page_path(route: &Utf8Path) -> Utf8PathBuf {
    let route = route.as_str().trim_start_matches('/').trim_end_matches('/');
    if route.is_empty() {
        Utf8PathBuf::from("index.html")
    } else {
        Utf8Path::new(route).join("index.html")
    }
}

fn validate_output_path(path: Utf8PathBuf) -> Result<Utf8PathBuf, OutputPathError> {
    let normalized = normalize_path(&path);
    let safe = !path.as_str().is_empty()
        && !path.as_str().split('/').any(|component| component == ".")
        && normalized == path
        && path
            .components()
            .all(|component| matches!(component, Utf8Component::Normal(_)));

    if safe {
        Ok(path)
    } else {
        Err(OutputPathError::UnsafePath(path))
    }
}

/// Builder returned by [`Output::to`], [`Output::page`], and [`Output::file`].
///
/// Pick the content method that matches what you generated:
///
/// - [`OutputTargetBuilder::html`] for rendered HTML pages.
/// - [`OutputTargetBuilder::text`] for UTF-8 text files such as RSS or JSON.
/// - [`OutputTargetBuilder::bytes`] for binary files.
pub struct OutputTargetBuilder {
    target: OutputTarget,
}

impl OutputTargetBuilder {
    /// Creates a UTF-8 HTML output at this target.
    ///
    /// For page targets, the route is converted to a pretty URL path:
    /// `/posts/hello/` becomes `posts/hello/index.html`. For file targets, the
    /// file path is kept exactly as requested.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), hauchiwa::output::OutputPathError> {
    /// use hauchiwa::Output;
    ///
    /// let output = Output::to("/posts/hello/").html("<h1>Hello</h1>")?;
    /// assert_eq!(output.path.as_str(), "posts/hello/index.html");
    ///
    /// let output = Output::to("feed.xml").html("<feed />")?;
    /// assert_eq!(output.path.as_str(), "feed.xml");
    /// # Ok(())
    /// # }
    /// ```
    pub fn html(self, data: impl Into<String>) -> Result<Output, OutputPathError> {
        Ok(Output {
            path: self.target.into_dist_path()?,
            data: OutputData::Utf8(data.into()),
        })
    }

    /// Creates a UTF-8 text output at this target.
    ///
    /// Use this for text-like non-HTML files where the destination should still
    /// be described with the fluent target API.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), hauchiwa::output::OutputPathError> {
    /// use hauchiwa::Output;
    ///
    /// let output = Output::file("robots.txt").text("User-agent: *")?;
    /// assert_eq!(output.path.as_str(), "robots.txt");
    /// # Ok(())
    /// # }
    /// ```
    pub fn text(self, data: impl Into<String>) -> Result<Output, OutputPathError> {
        Ok(Output {
            path: self.target.into_dist_path()?,
            data: OutputData::Utf8(data.into()),
        })
    }

    /// Creates a binary output at this target.
    ///
    /// Binary outputs are usually exact files, so this is most commonly paired
    /// with [`Output::file`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), hauchiwa::output::OutputPathError> {
    /// use hauchiwa::Output;
    ///
    /// let output = Output::file("downloads/archive.zip").bytes([1, 2, 3])?;
    /// assert_eq!(output.path.as_str(), "downloads/archive.zip");
    /// # Ok(())
    /// # }
    /// ```
    pub fn bytes(self, data: impl Into<Vec<u8>>) -> Result<Output, OutputPathError> {
        Ok(Output {
            path: self.target.into_dist_path()?,
            data: OutputData::Binary(data.into()),
        })
    }
}

/// The content of an [`Output`] file.
#[derive(Debug, Clone, Hash)]
pub enum OutputData {
    /// Text content (UTF-8).
    Utf8(String),
    /// Binary content (raw bytes).
    Binary(Vec<u8>),
}

impl AsRef<[u8]> for OutputData {
    fn as_ref(&self) -> &[u8] {
        match self {
            OutputData::Utf8(s) => s.as_bytes(),
            OutputData::Binary(b) => b.as_slice(),
        }
    }
}

/// Represents a single output file to be written to the `dist` directory.
///
/// A `Output` is a common output type for tasks that generate HTML, TXT, or
/// other static assets. The build system collects all `Output` instances and
/// writes them to the filesystem.
#[derive(Debug, Clone, Hash)]
pub struct Output {
    /// The destination path of the file, relative to the `dist` directory.
    pub path: Utf8PathBuf,
    /// The content of the file to be written.
    pub data: OutputData,
}

impl Output {
    /// Starts an output builder for a route, file path, or document.
    ///
    /// This is the ergonomic constructor for task output. It accepts:
    ///
    /// - A web route such as `"/posts/hello/"` or `"posts/hello"`, which writes
    ///   to `posts/hello/index.html`.
    /// - A file path with an extension such as `"feed.xml"`, which writes to
    ///   that exact path.
    /// - A loaded document or document metadata, which writes to the document's
    ///   generated `href`.
    ///
    /// When the distinction matters, prefer [`Output::page`] for routes and
    /// [`Output::file`] for exact file paths.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), hauchiwa::output::OutputPathError> {
    /// use hauchiwa::Output;
    ///
    /// let page = Output::to("/about/").html("<h1>About</h1>")?;
    /// assert_eq!(page.path.as_str(), "about/index.html");
    ///
    /// let feed = Output::to("feed.xml").text("<rss />")?;
    /// assert_eq!(feed.path.as_str(), "feed.xml");
    /// # Ok(())
    /// # }
    /// ```
    pub fn to(target: impl IntoOutputTarget) -> OutputTargetBuilder {
        OutputTargetBuilder {
            target: target.into_output_target(),
        }
    }

    /// Starts an output builder for a pretty HTML route.
    ///
    /// The route may have leading or trailing slashes. It is always written as
    /// an `index.html` file below `dist`:
    ///
    /// - `"/"` and `""` become `index.html`.
    /// - `"/posts/hello/"` and `"posts/hello"` become
    ///   `posts/hello/index.html`.
    ///
    /// Use this when a path has a dot in it but should still be treated as a
    /// route, or when you want to make the route-vs-file distinction explicit.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), hauchiwa::output::OutputPathError> {
    /// use hauchiwa::Output;
    ///
    /// let output = Output::page("posts/hello").html("<article />")?;
    /// assert_eq!(output.path.as_str(), "posts/hello/index.html");
    /// # Ok(())
    /// # }
    /// ```
    pub fn page(route: impl Into<Utf8PathBuf>) -> OutputTargetBuilder {
        OutputTargetBuilder {
            target: OutputTarget::page(route),
        }
    }

    /// Starts an output builder for an exact file path below `dist`.
    ///
    /// Unlike [`Output::page`], this does not append `index.html` or apply
    /// pretty URL handling. The path must be a safe relative path inside the
    /// configured output directory.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), hauchiwa::output::OutputPathError> {
    /// use hauchiwa::Output;
    ///
    /// let output = Output::file("assets/site.webmanifest").text("{}")?;
    /// assert_eq!(output.path.as_str(), "assets/site.webmanifest");
    /// # Ok(())
    /// # }
    /// ```
    pub fn file(path: impl Into<Utf8PathBuf>) -> OutputTargetBuilder {
        OutputTargetBuilder {
            target: OutputTarget::file(path),
        }
    }

    /// Starts a builder to create an Output from a source path.
    pub fn mapper(source: impl Into<Utf8PathBuf>) -> OutputBuilder {
        OutputBuilder {
            current: source.into(),
        }
    }

    /// Creates a new output with a normalized URL, suitable for HTML files.
    ///
    /// The path is automatically adjusted to create "pretty URLs". For example:
    /// - `foo/bar.html` becomes `foo/bar/index.html`
    /// - `foo/index.html` remains `foo/index.html`
    pub fn html(path: impl AsRef<Utf8Path>, data: impl Into<String>) -> Self {
        Self {
            path: normalize_path_html(path),
            data: OutputData::Utf8(data.into()),
        }
    }

    /// Creates a new output with a raw, unmodified path.
    ///
    /// This constructor is suitable for binary assets where the output path
    /// should not be altered, and the file content is provided as raw bytes.
    pub fn binary(path: impl Into<Utf8PathBuf>, data: impl Into<Vec<u8>>) -> Self {
        Self {
            path: path.into(),
            data: OutputData::Binary(data.into()),
        }
    }
}

/// A builder for transforming a source path into a destination [`Output`].
///
/// Created by [`Output::mapper`]. Chain `.strip_prefix()`, `.html()`, or `.ext()`
/// to shape the output path, then call `.content()` to finalise.
pub struct OutputBuilder {
    current: Utf8PathBuf,
}

impl OutputBuilder {
    /// Removes a prefix from the path (e.g., "content/").
    pub fn strip_prefix(
        mut self,
        prefix: impl AsRef<Utf8Path>,
    ) -> Result<Self, std::path::StripPrefixError> {
        self.current = self
            .current
            .strip_prefix(prefix.as_ref())
            .map(|p| p.to_path_buf())?;
        Ok(self)
    }

    /// Applies "Pretty URL" formatting (slugification).
    /// `posts/hello.md` -> `posts/hello/index.html`
    pub fn html(mut self) -> Self {
        self.current = source_to_bundle(&self.current)
            .join("index")
            .with_extension("html");
        self
    }

    /// Sets the file extension explicitly.
    pub fn ext(mut self, extension: &str) -> Self {
        self.current.set_extension(extension);
        self
    }

    /// Finalizes the path and attaches content to produce the Output.
    pub fn content(self, body: impl Into<String>) -> Output {
        // If it's HTML, we ensure it ends in index.html for the server
        let path = if (self.current.extension() == Some("html"))
            || self.current.file_name() == Some("index")
        {
            normalize_path_html(&self.current)
        } else {
            // For non-html assets, normalize just cleans . and ..
            normalize_path(&self.current)
        };

        Output {
            path,
            data: OutputData::Utf8(body.into()),
        }
    }
}

/// A trait for handles that can be flattened into a list of Output references.
pub trait OutputHandle: Handle {
    /// Extracts a list of `Output` references from the handle's resolved value.
    fn resolve_refs(item: &Dynamic) -> (Option<TrackerPtr>, Vec<&Output>);
}

impl OutputHandle for One<Output> {
    fn resolve_refs(item: &Dynamic) -> (Option<TrackerPtr>, Vec<&Output>) {
        match item.downcast_ref::<Output>() {
            Some(item) => (None, vec![item]),
            None => unreachable!(),
        }
    }
}

impl OutputHandle for One<Vec<Output>> {
    fn resolve_refs(item: &Dynamic) -> (Option<TrackerPtr>, Vec<&Output>) {
        match item.downcast_ref::<Vec<Output>>() {
            Some(item) => (None, item.iter().collect()),
            None => unreachable!(),
        }
    }
}

impl OutputHandle for Many<Output> {
    fn resolve_refs(item: &Dynamic) -> (Option<TrackerPtr>, Vec<&Output>) {
        match item.downcast_ref::<Map<Output>>() {
            Some(map) => {
                let ptr = TrackerPtr::default();
                let mut items = Vec::new();

                {
                    #[allow(clippy::unwrap_used)]
                    // poisoned mutex means a thread panicked - unrecoverable
                    let mut tracker = ptr.ptr.lock().unwrap();

                    for (key, (output, provenance)) in &map.map {
                        tracker.accessed.insert(key.clone(), *provenance);
                        items.push(output);
                    }
                }

                (Some(ptr), items)
            }
            None => unreachable!(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_source_to_href() {
        // Simple file
        assert_eq!(
            source_to_href(Utf8Path::new("content/posts/hello.md"), Some("content")),
            "/posts/hello/"
        );

        // Index file
        assert_eq!(
            source_to_href(Utf8Path::new("content/posts/index.md"), Some("content")),
            "/posts/"
        );

        // No base
        assert_eq!(
            source_to_href(Utf8Path::new("posts/hello.md"), None),
            "/posts/hello/"
        );

        // Root index
        assert_eq!(source_to_href(Utf8Path::new("index.md"), None), "/");

        // Double slash edge case (e.g. parent is empty after base strip, but it's not index)
        assert_eq!(
            source_to_href(Utf8Path::new("content/hello.md"), Some("content")),
            "/hello/"
        );

        // Double slash edge case with index
        assert_eq!(
            source_to_href(Utf8Path::new("content/index.md"), Some("content")),
            "/"
        );

        // Deeply nested
        assert_eq!(
            source_to_href(Utf8Path::new("content/a/b/c.md"), Some("content")),
            "/a/b/c/"
        );
    }

    #[test]
    fn test_source_to_bundle() {
        // Standard file
        assert_eq!(
            source_to_bundle("content/foo/bar.md"),
            Utf8Path::new("content/foo/bar")
        );

        // Index file
        assert_eq!(
            source_to_bundle("content/foo/index.md"),
            Utf8Path::new("content/foo")
        );

        // Root index
        assert_eq!(source_to_bundle("index.md"), Utf8Path::new(""));
    }

    #[test]
    fn test_href_to_dist() {
        // Standard href
        assert_eq!(
            href_to_dist("/posts/hello/", "dist"),
            Utf8Path::new("dist/posts/hello/index.html")
        );

        // Root href
        assert_eq!(href_to_dist("/", "dist"), Utf8Path::new("dist/index.html"));

        // Nested href
        assert_eq!(
            href_to_dist("/a/b/c/", "dist"),
            Utf8Path::new("dist/a/b/c/index.html")
        );
    }

    #[test]
    fn test_output_to_route_html() -> Result<(), OutputPathError> {
        let page = Output::to("/posts/hello/").html("hello")?;
        assert_eq!(page.path, Utf8Path::new("posts/hello/index.html"));

        let page = Output::to("posts").html("hello")?;
        assert_eq!(page.path, Utf8Path::new("posts/index.html"));

        let page = Output::to("").html("hello")?;
        assert_eq!(page.path, Utf8Path::new("index.html"));
        Ok(())
    }

    #[test]
    fn test_output_to_file_text_and_bytes() -> Result<(), OutputPathError> {
        let text = Output::to("posts/rss.xml").text("<rss />")?;
        assert_eq!(text.path, Utf8Path::new("posts/rss.xml"));
        assert!(matches!(text.data, OutputData::Utf8(_)));

        let bytes = Output::file("files/archive.zip").bytes([1, 2, 3])?;
        assert_eq!(bytes.path, Utf8Path::new("files/archive.zip"));
        assert!(matches!(bytes.data, OutputData::Binary(_)));
        Ok(())
    }

    #[test]
    fn test_output_to_rejects_unsafe_paths() {
        assert!(Output::file("../escape.txt").text("bad").is_err());
        assert!(Output::file("same/./file.txt").text("bad").is_err());
    }

    #[test]
    fn test_output_to_document_html() -> Result<(), OutputPathError> {
        let document = crate::loader::generic::Document {
            matter: Box::new(()),
            text: String::new(),
            meta: crate::loader::generic::DocumentMeta {
                path: Utf8PathBuf::from("content/posts/hello.md"),
                base: Some("content".into()),
                href: "/posts/hello/".to_string(),
            },
        };

        let page = Output::to(&document).html("hello")?;
        assert_eq!(page.path, Utf8Path::new("posts/hello/index.html"));

        let page = Output::to(&document.meta).html("hello")?;
        assert_eq!(page.path, Utf8Path::new("posts/hello/index.html"));

        let document_ref = &document;
        fn from_double_ref(
            document: &&crate::loader::generic::Document<()>,
        ) -> Result<Output, OutputPathError> {
            Output::to(document).html("hello")
        }

        let page = from_double_ref(&document_ref)?;
        assert_eq!(page.path, Utf8Path::new("posts/hello/index.html"));
        Ok(())
    }
}