typst-pack 0.5.0

Portable single-file packs of Typst projects: sources, resources, packages, and fonts
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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
//! The reference filesystem Pack Assembler.
//!
//! The adapter reads and the core transforms. It lists and reads the
//! project, composes the Font Catalog out of the font sources the
//! host offers, obtains the Package Trees the core reports as
//! missing, and resolves Document Time; Pack Creation itself runs in
//! the core over those bytes.
//!
//! Each read value records the exact bytes observed by its source adapter;
//! the project reader does not reread the source solely to establish that all
//! values coexisted at one instant.

#![cfg(feature = "fs")]

use std::collections::HashSet;
use std::fmt;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;

use ecow::EcoVec;
use typst::diag::{FileError, FileResult, SourceDiagnostic};
use typst::foundations::{Bytes, Datetime, Dict, Duration};
use typst::syntax::package::PackageSpec;
use typst::syntax::{FileId, RootedPath, Source, VirtualPath, VirtualRoot};
use typst::text::{Font, FontBook};
use typst::utils::LazyHash;
use typst::{Feature, Library, LibraryExt, World};
use typst_kit::files::{FileLoader, FileStore};
use typst_kit::fonts::FontStore;

use crate::creation::{
    DiscoverySpecification, PackCreationError, PackCreationInput, PackCreationOutcome, create,
};
use crate::domain::{DocumentTime, TypstTarget};
use crate::font_catalog::FontDisposition;
use crate::fs_fonts::{FilesystemFontLimits, FilesystemFontSource, read_filesystem_fonts};
use crate::fs_packages::{
    FilesystemPackageAuthority, FilesystemPackageAuthorityReadError, FilesystemPackageLimits,
    ReadPackages,
};
use crate::fs_project;
use crate::manifest::PackMetadata;
use crate::pack::Pack;
use crate::package_catalog::{PackageCatalog, PackageCatalogError, PackageDisposition};
use crate::package_failure::PackageReadFailures;
use crate::project_snapshot::ProjectSnapshot;

/// Named finite resource policy for one filesystem Pack Assembly run.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FilesystemPackAssemblyProfile {
    project: fs_project::FilesystemProjectLimits,
    packages: FilesystemPackageLimits,
    fonts: FilesystemFontLimits,
    #[cfg(feature = "egress")]
    package_expansion: crate::PackageExpansionLimits,
}

impl FilesystemPackAssemblyProfile {
    /// The first-party finite profile used by ordinary filesystem workflows.
    pub const fn reference_v1() -> Self {
        Self {
            project: fs_project::FilesystemProjectLimits::reference_v1(),
            packages: FilesystemPackageLimits::reference_v1(),
            fonts: FilesystemFontLimits::reference_v1(),
            #[cfg(feature = "egress")]
            package_expansion: crate::PackageExpansionLimits::reference_v1(),
        }
    }

    pub const fn project(&self) -> fs_project::FilesystemProjectLimits {
        self.project
    }

    pub const fn packages(&self) -> FilesystemPackageLimits {
        self.packages
    }

    pub const fn fonts(&self) -> FilesystemFontLimits {
        self.fonts
    }

    #[cfg(feature = "egress")]
    pub const fn package_expansion(&self) -> crate::PackageExpansionLimits {
        self.package_expansion
    }
}

/// Clock policy used when a run does not supply an exact Document Time.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[non_exhaustive]
pub enum FilesystemPackAssemblyClock {
    /// Resolve the current UNIX timestamp from the host clock for each run.
    #[default]
    System,
    /// Reuse one exact configured Document Time for every run.
    Fixed(DocumentTime),
}

/// Reusable host policy for the reference filesystem Pack Assembler.
#[derive(Debug)]
pub struct FilesystemPackAssemblerConfig {
    font_paths: Vec<PathBuf>,
    system_fonts: bool,
    typst_embedded_fonts: bool,
    package_path: Option<PathBuf>,
    package_cache_path: Option<PathBuf>,
    offline: bool,
    #[cfg(feature = "egress")]
    certificate: Option<PathBuf>,
    clock: FilesystemPackAssemblyClock,
    profile: FilesystemPackAssemblyProfile,
}

impl FilesystemPackAssemblerConfig {
    /// Starts with ordinary first-party host policy and the reference-v1
    /// finite profile.
    pub fn new() -> Self {
        Self {
            font_paths: Vec::new(),
            system_fonts: true,
            typst_embedded_fonts: true,
            package_path: None,
            package_cache_path: None,
            offline: false,
            #[cfg(feature = "egress")]
            certificate: None,
            clock: FilesystemPackAssemblyClock::System,
            profile: FilesystemPackAssemblyProfile::reference_v1(),
        }
    }

    /// Selects the finite resource policy applied to every run.
    pub fn profile(mut self, profile: FilesystemPackAssemblyProfile) -> Self {
        self.profile = profile;
        self
    }

    /// Selects how omitted per-run Document Time is resolved.
    pub fn clock(mut self, clock: FilesystemPackAssemblyClock) -> Self {
        self.clock = clock;
        self
    }

    /// Adds a directory to the configured Font Authority.
    pub fn font_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.font_paths.push(path.into());
        self
    }

    /// Whether the configured Font Authority scans host system fonts.
    pub fn system_fonts(mut self, system: bool) -> Self {
        self.system_fonts = system;
        self
    }

    /// Whether the configured Font Authority offers Typst's embedded fonts.
    pub fn typst_embedded_fonts(mut self, include: bool) -> Self {
        self.typst_embedded_fonts = include;
        self
    }

    /// Overrides the directory in which locally installed packages are
    /// searched (namespace/name/version layout).
    pub fn package_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.package_path = Some(path.into());
        self
    }

    /// Overrides the directory in which downloaded packages are cached.
    ///
    /// This configures both cache reads and the destination of successful
    /// downloads. A build without egress can still read the selected cache.
    pub fn package_cache_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.package_cache_path = Some(path.into());
        self
    }

    /// Disallows network access during creation. Defaults to
    /// `false`.
    ///
    /// When enabled, package dependencies must already exist in the local
    /// package directories or package cache; anything that would need to be
    /// downloaded fails the compile as not found. A build without the `egress`
    /// feature behaves this way regardless, having no transport to reach the
    /// network with, so setting this stays available either way.
    pub fn offline(mut self, offline: bool) -> Self {
        self.offline = offline;
        self
    }

    /// Configures a custom CA certificate for package downloads.
    ///
    /// Only a download presents a certificate to verify, so this needs the
    /// `egress` feature.
    #[cfg(feature = "egress")]
    pub fn certificate(mut self, path: Option<PathBuf>) -> Self {
        self.certificate = path;
        self
    }
}

impl Default for FilesystemPackAssemblerConfig {
    fn default() -> Self {
        Self::new()
    }
}

/// Per-run roots, Discovery Specification controls, embedding choices, and
/// Pack metadata.
pub struct FilesystemPackAssemblyRequest<'a> {
    root: &'a Path,
    entrypoint: &'a Path,
    vendor_packages: bool,
    embed_fonts: bool,
    include_typst_embedded_fonts: bool,
    inputs: Dict,
    features: Vec<Feature>,
    target: TypstTarget,
    document_time: Option<DocumentTime>,
    timings: Option<PathBuf>,
    metadata: Option<PackMetadata>,
}

impl<'a> FilesystemPackAssemblyRequest<'a> {
    /// Starts one run for an entrypoint that is absolute or relative to `root`.
    pub fn new(root: &'a Path, entrypoint: &'a Path) -> Self {
        Self {
            root,
            entrypoint,
            vendor_packages: true,
            embed_fonts: false,
            include_typst_embedded_fonts: false,
            inputs: Dict::new(),
            features: Vec::new(),
            target: TypstTarget::Paged,
            document_time: None,
            timings: None,
            metadata: None,
        }
    }

    /// Whether selected Package Trees are embedded in the Pack.
    pub fn vendor_packages(mut self, vendor: bool) -> Self {
        self.vendor_packages = vendor;
        self
    }

    /// Whether selected scanned and system Font Containers are embedded.
    pub fn embed_fonts(mut self, embed: bool) -> Self {
        self.embed_fonts = embed;
        self
    }

    /// Whether embedding includes selected Typst-embedded Font Containers.
    pub fn include_typst_embedded_fonts(mut self, include: bool) -> Self {
        self.include_typst_embedded_fonts = include;
        self
    }

    /// Values made available to document code as `sys.inputs` during discovery.
    pub fn inputs(mut self, inputs: Dict) -> Self {
        self.inputs = inputs;
        self
    }

    /// Enables one Typst engine feature during discovery.
    pub fn feature(mut self, feature: Feature) -> Self {
        self.features.push(feature);
        self
    }

    /// Selects the Typst Target for discovery.
    pub fn target(mut self, target: TypstTarget) -> Self {
        self.target = target;
        self
    }

    /// Supplies an exact Document Time instead of resolving the host clock.
    pub fn document_time(mut self, document_time: DocumentTime) -> Self {
        self.document_time = Some(document_time);
        self
    }

    /// Writes creation performance timings to a Perfetto-compatible JSON file.
    pub fn timings(mut self, path: Option<PathBuf>) -> Self {
        self.timings = path;
        self
    }

    /// Sets descriptive metadata recorded in the pack manifest.
    pub fn metadata(mut self, metadata: PackMetadata) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

/// Reusable filesystem Pack Assembly over configured concrete authorities.
///
/// One assembler holds the host policy — font paths, package directories, the
/// clock, and the finite profile — and serves many requests. It runs Dependency
/// Discovery and repeats [`create`](crate::create) until it produces a Pack.
///
/// ```no_run
/// use std::path::Path;
///
/// use typst_pack::pack_archive::encode;
/// use typst_pack::{
///     FilesystemPackAssembler, FilesystemPackAssemblerConfig, FilesystemPackAssemblyRequest,
/// };
///
/// # fn run() -> Result<(), Box<dyn std::error::Error>> {
/// let assembler = FilesystemPackAssembler::new(FilesystemPackAssemblerConfig::new());
/// let report = assembler.assemble(
///     FilesystemPackAssemblyRequest::new(Path::new("path/to/project"), Path::new("main.typ"))
///         .embed_fonts(true),
/// )?;
///
/// for warning in report.warnings() {
///     eprintln!("discovery warning: {}", warning.message);
/// }
///
/// let archive = encode(report.pack())?;
/// std::fs::write("project.typk", archive.as_slice())?;
/// # Ok(())
/// # }
/// ```
pub struct FilesystemPackAssembler {
    authority: FilesystemPackageAuthority,
    font_paths: Vec<PathBuf>,
    system_fonts: bool,
    typst_embedded_fonts: bool,
    clock: FilesystemPackAssemblyClock,
    profile: FilesystemPackAssemblyProfile,
    #[cfg(test)]
    after_creation_hook: Option<Box<dyn Fn()>>,
}

impl FilesystemPackAssembler {
    /// Configures the concrete project, package, font, clock, and finite-profile
    /// policy reused by each assembly request.
    pub fn new(config: FilesystemPackAssemblerConfig) -> Self {
        let authority = FilesystemPackageAuthority::with_limits(
            config.package_path.as_deref(),
            config.package_cache_path.as_deref(),
            config.offline,
            config.profile.packages,
            #[cfg(feature = "egress")]
            config.profile.package_expansion,
        );
        #[cfg(feature = "egress")]
        let authority = authority.certificate(config.certificate);
        Self {
            authority,
            font_paths: config.font_paths,
            system_fonts: config.system_fonts,
            typst_embedded_fonts: config.typst_embedded_fonts,
            clock: config.clock,
            profile: config.profile,
            #[cfg(test)]
            after_creation_hook: None,
        }
    }

    #[cfg(test)]
    pub(crate) fn after_creation_hook(mut self, hook: impl Fn() + 'static) -> Self {
        self.after_creation_hook = Some(Box::new(hook));
        self
    }

    /// Reads one Project Snapshot and Font Catalog, then resolves exactly the
    /// packages reported between stateless Pack Creation invocations.
    pub fn assemble(
        &self,
        request: FilesystemPackAssemblyRequest<'_>,
    ) -> Result<PackAssemblyReport, FilesystemPackAssemblyError> {
        let (result, timing_error) = self.assemble_with_timing(request);
        timing_error.map_or(result, Err)
    }

    #[doc(hidden)]
    pub fn assemble_with_timing(
        &self,
        request: FilesystemPackAssemblyRequest<'_>,
    ) -> (
        Result<PackAssemblyReport, FilesystemPackAssemblyError>,
        Option<FilesystemPackAssemblyError>,
    ) {
        let mut timing_error = None;
        let result = self.assemble_inner(request, &mut timing_error);
        (result, timing_error)
    }

    fn assemble_inner(
        &self,
        request: FilesystemPackAssemblyRequest<'_>,
        timing_error: &mut Option<FilesystemPackAssemblyError>,
    ) -> Result<PackAssemblyReport, FilesystemPackAssemblyError> {
        let root = request.root.canonicalize().map_err(|err| {
            FilesystemPackAssemblyError::io("failed to resolve project root", err)
        })?;
        let entrypoint_abs = if request.entrypoint.is_absolute() {
            request.entrypoint.to_owned()
        } else {
            root.join(request.entrypoint)
        };
        let entrypoint_abs = entrypoint_abs
            .canonicalize()
            .map_err(|err| FilesystemPackAssemblyError::io("failed to resolve entrypoint", err))?;
        let entrypoint = VirtualPath::virtualize(&root, &entrypoint_abs)
            .map_err(|_| FilesystemPackAssemblyError::OutsideRoot(entrypoint_abs.clone()))?;
        let snapshot = Arc::new(fs_project::read_filesystem_project(
            &root,
            entrypoint.get_without_slash(),
            self.profile.project,
        )?);

        let packages = Arc::new(ReadPackages::new());

        let scanned_disposition = FontDisposition::embedded_if(request.embed_fonts);
        let mut font_sources = Vec::new();
        if self.system_fonts {
            font_sources.push(FilesystemFontSource::system(scanned_disposition));
        }
        #[cfg(feature = "embedded-fonts")]
        if self.typst_embedded_fonts {
            font_sources.push(FilesystemFontSource::typst_embedded(
                FontDisposition::embedded_if(
                    request.embed_fonts && request.include_typst_embedded_fonts,
                ),
            ));
        }
        #[cfg(not(feature = "embedded-fonts"))]
        let _ = (
            self.typst_embedded_fonts,
            request.include_typst_embedded_fonts,
        );
        font_sources.extend(
            self.font_paths
                .iter()
                .map(|path| FilesystemFontSource::directory(path, scanned_disposition)),
        );
        let font_catalog = read_filesystem_fonts(font_sources, self.profile.fonts)?;

        // The core consults no wall clock, so the adapter resolves the
        // representative request's Document Time from the host's.
        let document_time = request
            .document_time
            .unwrap_or_else(|| self.clock.document_time());

        let discovery = DiscoverySpecification::new(
            request.target,
            request.inputs,
            document_time,
            request.features,
        )
        .map_err(|source| {
            FilesystemPackAssemblyError::DiscoverySpecification(
                FilesystemPackAssemblyDiscoveryError { source },
            )
        })?;

        let mut world = ReadWorld {
            root: root.clone(),
            #[cfg(feature = "diagnostics")]
            workdir: std::env::current_dir()
                .ok()
                .map(|path| path.canonicalize().unwrap_or(path)),
            library: LazyHash::new(Library::builder().build()),
            main: RootedPath::new(VirtualRoot::Project, entrypoint).intern(),
            files: FileStore::new(ReadLoader {
                project: Arc::clone(&snapshot),
                packages: Arc::clone(&packages),
            }),
            fonts: FontStore::new(),
        };

        let disposition = if request.vendor_packages {
            PackageDisposition::Embedded
        } else {
            PackageDisposition::External
        };
        let mut timer = typst_kit::timer::Timer::new_or_placeholder(request.timings);
        let mut creation = None;
        let timings = timer.record(&mut world, |_| {
            creation = Some(resolve_and_create(
                &snapshot,
                &font_catalog,
                &discovery,
                request.metadata.as_ref(),
                &self.authority,
                &packages,
                disposition,
            ));
        });
        let Some(creation) = creation else {
            return Err(FilesystemPackAssemblyError::Timings(
                timings
                    .expect_err("timer did not execute creation")
                    .to_string(),
            ));
        };
        *timing_error = timings
            .err()
            .map(|error| FilesystemPackAssemblyError::Timings(error.to_string()));
        let (pack, warnings) = match creation {
            Ok(created) => created,
            Err(error) => return Err(error.into_assembly_error(world)),
        };

        #[cfg(test)]
        if let Some(hook) = &self.after_creation_hook {
            hook();
        }

        Ok(PackAssemblyReport {
            pack,
            warnings,
            #[cfg(feature = "diagnostics")]
            world,
        })
    }
}

impl FilesystemPackAssemblyClock {
    fn document_time(self) -> DocumentTime {
        match self {
            Self::System => {
                let timestamp = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map_or(0, |duration| duration.as_secs() as i64);
                DocumentTime::UnixTimestamp(timestamp)
            }
            Self::Fixed(document_time) => document_time,
        }
    }
}

/// Runs creation over the read inputs, resolving what it reports as
/// missing, until it issues a Pack.
///
/// Package requirements can only be discovered by compiling, so each round
/// reports the exact specifications no supplied tree covers, the adapter
/// obtains them through the Package Authority, and creation runs again over
/// the larger set. Every round therefore either issues a Pack, adds a tree the
/// request did not have, declares one the Package Authority could not resolve,
/// or fails.
///
/// A specification the authority cannot resolve is declared rather than
/// returned. The next round's representative request then fails at the import
/// that needed it, carrying the authority's own reason, so an unresolvable
/// package is reported where the document asked for it exactly as it was
/// before package resolution moved out of the representative compile.
fn resolve_and_create(
    project: &ProjectSnapshot,
    fonts: &crate::font_catalog::FontCatalog,
    discovery: &DiscoverySpecification,
    metadata: Option<&PackMetadata>,
    authority: &FilesystemPackageAuthority,
    packages: &ReadPackages,
    disposition: PackageDisposition,
) -> Result<(Pack, EcoVec<SourceDiagnostic>), CreationFailure> {
    let mut attempted_specs: HashSet<String> = HashSet::new();
    let mut package_failures = Vec::new();
    let mut read_failures = PackageReadFailures::new();
    let mut catalog = PackageCatalog::new();
    loop {
        let outcome = create(PackCreationInput {
            project,
            packages: &catalog,
            fonts,
            package_failures: &read_failures,
            discovery,
            metadata,
        })
        .map_err(|error| CreationFailure::Core {
            error,
            package_failures: std::mem::take(&mut package_failures),
        })?;
        match outcome {
            PackCreationOutcome::Created { pack, warnings } => return Ok((pack, warnings)),
            PackCreationOutcome::MissingPackageSpecifications(missing) => {
                for spec in missing {
                    if !attempted_specs.insert(spec.to_string()) {
                        // Creation reports neither what a supplied tree covers
                        // nor what was declared unresolvable, so this cannot
                        // repeat; failing keeps that a diagnosis rather than a
                        // loop that never progresses.
                        return Err(CreationFailure::Adapter(
                            FilesystemPackAssemblyError::Package {
                                message: "the representative creation compile did not accept the \
                                      resolved package tree"
                                    .to_owned(),
                                spec,
                            },
                        ));
                    }
                    match authority.read(&spec) {
                        Ok(read) => {
                            let (tree, _) = read.into_parts();
                            packages.record(spec.clone(), tree.clone());
                            read_failures.remove(&spec);
                            catalog
                                .insert(spec.clone(), tree, disposition)
                                .map_err(FilesystemPackAssemblyError::InvalidPackageCatalog)?;
                        }
                        Err(error) => {
                            read_failures.insert(error.failure().clone());
                            package_failures.push(error);
                        }
                    }
                }
            }
        }
    }
}

/// A failure that ended one creation loop, before the adapter dressed it in
/// its own vocabulary.
enum CreationFailure {
    /// The core issued no Pack.
    Core {
        error: PackCreationError,
        package_failures: Vec<FilesystemPackageAuthorityReadError>,
    },
    /// The adapter failed to read what the core reported as missing.
    Adapter(FilesystemPackAssemblyError),
}

impl CreationFailure {
    /// Reports the failure in the filesystem adapter's vocabulary, handing a
    /// failed representative compile the sources that render its diagnostics.
    fn into_assembly_error(self, world: ReadWorld) -> FilesystemPackAssemblyError {
        match self {
            Self::Adapter(error) => error,
            Self::Core {
                error,
                package_failures,
            } => FilesystemPackAssemblyError::Creation(FilesystemPackAssemblyCreationError {
                context: Box::new(PackAssemblyDiagnosticContext { world }),
                error,
                package_failures,
            }),
        }
    }
}

impl From<FilesystemPackAssemblyError> for CreationFailure {
    fn from(error: FilesystemPackAssemblyError) -> Self {
        Self::Adapter(error)
    }
}

/// The terminal report of a successful filesystem Pack Assembly run.
pub struct PackAssemblyReport {
    pack: Pack,
    warnings: EcoVec<SourceDiagnostic>,
    #[cfg(feature = "diagnostics")]
    pub(crate) world: ReadWorld,
}

impl PackAssemblyReport {
    /// The assembled, authoritatively validated Pack.
    pub fn pack(&self) -> &Pack {
        &self.pack
    }

    /// Warnings emitted by the successful Dependency Discovery run.
    pub fn warnings(&self) -> &[SourceDiagnostic] {
        &self.warnings
    }

    /// Recovers the Pack and discovery warnings.
    pub fn into_parts(self) -> (Pack, EcoVec<SourceDiagnostic>) {
        (self.pack, self.warnings)
    }
}

/// Opaque source context retained for first-party creation diagnostics.
///
/// This value intentionally does not implement Typst's [`World`] interface.
#[derive(Debug)]
pub struct PackAssemblyDiagnosticContext {
    #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
    pub(crate) world: ReadWorld,
}

/// A Pack Creation failure retained by the filesystem Pack Assembler.
#[derive(Debug, thiserror::Error)]
#[error("{error}")]
pub struct FilesystemPackAssemblyCreationError {
    context: Box<PackAssemblyDiagnosticContext>,
    #[source]
    error: PackCreationError,
    package_failures: Vec<FilesystemPackageAuthorityReadError>,
}

impl FilesystemPackAssemblyCreationError {
    /// Opaque source context for first-party diagnostic rendering.
    pub fn context(&self) -> &PackAssemblyDiagnosticContext {
        &self.context
    }

    /// The unchanged core Pack Creation failure.
    pub fn error(&self) -> &PackCreationError {
        &self.error
    }

    /// Package Authority failures from the same assembly attempt.
    pub fn package_failures(&self) -> &[FilesystemPackageAuthorityReadError] {
        &self.package_failures
    }

    /// Recovers the diagnostic context, core error, and authority failures.
    pub fn into_parts(
        self,
    ) -> (
        Box<PackAssemblyDiagnosticContext>,
        PackCreationError,
        Vec<FilesystemPackageAuthorityReadError>,
    ) {
        (self.context, self.error, self.package_failures)
    }
}

/// An invalid Discovery Specification retained by filesystem Pack Assembly.
#[derive(Debug, thiserror::Error)]
#[error("invalid Discovery Specification: {source}")]
pub struct FilesystemPackAssemblyDiscoveryError {
    #[source]
    source: crate::creation::DiscoverySpecificationError,
}

impl FilesystemPackAssemblyDiscoveryError {
    /// The unchanged Discovery Specification construction failure.
    pub fn source_error(&self) -> &crate::creation::DiscoverySpecificationError {
        &self.source
    }

    /// Recovers the Discovery Specification construction failure.
    pub fn into_source(self) -> crate::creation::DiscoverySpecificationError {
        self.source
    }
}

/// A failure while packing a project directory.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum FilesystemPackAssemblyError {
    #[error("{message}: {source}")]
    Io {
        message: String,
        #[source]
        source: std::io::Error,
    },
    #[error("`{0}` is outside the project root and cannot be packed")]
    OutsideRoot(PathBuf),
    #[error(transparent)]
    Creation(FilesystemPackAssemblyCreationError),
    #[error(transparent)]
    DiscoverySpecification(FilesystemPackAssemblyDiscoveryError),
    #[error("failed to write creation timings: {0}")]
    Timings(String),
    #[error("failed to load package {spec}: {message}")]
    Package { spec: PackageSpec, message: String },
    /// The read Package Trees do not form a valid Package Catalog.
    #[error(transparent)]
    InvalidPackageCatalog(PackageCatalogError),
    #[error(transparent)]
    ProjectRead(#[from] fs_project::FilesystemProjectReadError),
    #[error(transparent)]
    FontRead(#[from] crate::fs_fonts::FilesystemFontReadError),
}

impl FilesystemPackAssemblyError {
    pub(crate) fn io(message: &str, source: std::io::Error) -> Self {
        Self::Io {
            message: message.to_owned(),
            source,
        }
    }
}

/// The bytes one creation read, as a world.
///
/// It compiles nothing: the representative request runs in the core, over the
/// same bytes. This world exists so that what the adapter read can still be
/// presented afterwards — creation diagnostics render their source context and
/// timing spans resolve their file and line from here, without reading the
/// project or a package tree a second time.
pub(crate) struct ReadWorld {
    root: PathBuf,
    #[cfg(feature = "diagnostics")]
    workdir: Option<PathBuf>,
    library: LazyHash<Library>,
    main: FileId,
    files: FileStore<ReadLoader>,
    fonts: FontStore,
}

impl ReadWorld {
    /// The canonicalized project root.
    #[cfg(feature = "diagnostics")]
    fn root(&self) -> &Path {
        &self.root
    }

    #[cfg(feature = "diagnostics")]
    fn workdir(&self) -> Option<&Path> {
        self.workdir.as_deref()
    }
}

impl fmt::Debug for ReadWorld {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ReadWorld")
            .field("root", &self.root)
            .finish_non_exhaustive()
    }
}

impl World for ReadWorld {
    fn library(&self) -> &LazyHash<Library> {
        &self.library
    }

    /// No face at all: presentation resolves file requests, never fonts.
    fn book(&self) -> &LazyHash<FontBook> {
        self.fonts.book()
    }

    fn main(&self) -> FileId {
        self.main
    }

    fn source(&self, id: FileId) -> FileResult<Source> {
        self.files.source(id)
    }

    fn file(&self, id: FileId) -> FileResult<Bytes> {
        self.files.file(id)
    }

    fn font(&self, _index: usize) -> Option<Font> {
        None
    }

    /// Absent: the representative request's Document Time is the core's, and
    /// presentation evaluates no document code.
    fn today(&self, _offset: Option<Duration>) -> Option<Datetime> {
        None
    }
}

#[cfg(feature = "diagnostics")]
impl typst_kit::diagnostics::DiagnosticWorld for ReadWorld {
    fn name(&self, id: FileId) -> String {
        match id.root() {
            VirtualRoot::Project => id
                .vpath()
                .realize(self.root())
                .ok()
                .and_then(|path| relative_path(&path, self.workdir()?))
                .map(|path| path.to_string_lossy().into_owned())
                .unwrap_or_else(|| display_file_id(id)),
            VirtualRoot::Package(_) => display_file_id(id),
        }
    }
}

#[cfg(feature = "diagnostics")]
fn display_file_id(id: FileId) -> String {
    match id.root() {
        VirtualRoot::Project => id.vpath().get_without_slash().to_owned(),
        VirtualRoot::Package(spec) => format!("{spec}{}", id.vpath().get_with_slash()),
    }
}

#[cfg(feature = "diagnostics")]
fn relative_path(path: &Path, base: &Path) -> Option<PathBuf> {
    if path.is_absolute() != base.is_absolute() {
        return path.is_absolute().then(|| path.to_path_buf());
    }

    let mut path_components = path.components();
    let mut base_components = base.components();
    let mut relative = Vec::new();
    loop {
        match (path_components.next(), base_components.next()) {
            (None, None) => break,
            (Some(component), None) => {
                relative.push(component);
                relative.extend(path_components.by_ref());
                break;
            }
            (None, Some(_)) => relative.push(std::path::Component::ParentDir),
            (Some(path), Some(base)) if relative.is_empty() && path == base => {}
            (Some(path), Some(std::path::Component::CurDir)) => relative.push(path),
            (Some(_), Some(std::path::Component::ParentDir)) => return None,
            (Some(std::path::Component::Prefix(_) | std::path::Component::RootDir), Some(_))
            | (Some(_), Some(std::path::Component::Prefix(_) | std::path::Component::RootDir)) => {
                return path.is_absolute().then(|| path.to_path_buf());
            }
            (Some(path), Some(_)) => {
                relative.push(std::path::Component::ParentDir);
                relative.extend(base_components.map(|_| std::path::Component::ParentDir));
                relative.push(path);
                relative.extend(path_components.by_ref());
                break;
            }
        }
    }

    Some(relative.iter().map(|part| part.as_os_str()).collect())
}

/// Serves file requests from the bytes the adapter read, and from nothing
/// else: no request reaches the filesystem a second time.
struct ReadLoader {
    project: Arc<ProjectSnapshot>,
    packages: Arc<ReadPackages>,
}

impl FileLoader for ReadLoader {
    fn load(&self, id: FileId) -> FileResult<Bytes> {
        let path = id.vpath().get_without_slash();
        match id.root() {
            VirtualRoot::Project => self.project.shared_file(path).map(|data| data.to_typst()),
            VirtualRoot::Package(spec) => self.packages.file(spec, path),
        }
        .ok_or_else(|| FileError::NotFound(PathBuf::from(path)))
    }
}