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
//! The pack manifest stored as `typst-pack.toml` inside the archive.

use std::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize};
use typst::syntax::package::PackageSpec;

/// The archive entry name of the manifest.
pub const MANIFEST_PATH: &str = "typst-pack.toml";

/// The pack format version this crate reads and writes.
pub const FORMAT_VERSION: u32 = 1;

/// The parsed contents of `typst-pack.toml`.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) struct PackManifest {
    /// The pack format version. Readers must reject versions they don't know.
    format_version: u32,
    /// The packed Typst project.
    project: ProjectManifest,
    /// Package dependencies observed while creating the pack.
    #[serde(default, skip_serializing_if = "PackagesManifest::is_empty")]
    packages: PackagesManifest,
    /// Fonts embedded in the pack.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    fonts: Vec<FontManifest>,
    /// Optional descriptive metadata about the packed project.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    metadata: Option<PackMetadata>,
}

#[derive(Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct Version1Manifest {
    format_version: u32,
    project: ProjectManifest,
    #[serde(default)]
    packages: Version1PackagesManifest,
    #[serde(default)]
    fonts: Vec<FontManifest>,
    #[serde(default)]
    metadata: Option<PackMetadata>,
}

impl TryFrom<Version1Manifest> for PackManifest {
    type Error = PackManifestError;

    fn try_from(manifest: Version1Manifest) -> Result<Self, Self::Error> {
        Ok(Self {
            format_version: manifest.format_version,
            project: manifest.project,
            packages: manifest.packages.try_into()?,
            fonts: manifest.fonts,
            metadata: manifest.metadata,
        })
    }
}

impl<'de> Deserialize<'de> for PackManifest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = toml::Value::deserialize(deserializer)?;
        parse_manifest_value(value).map_err(serde::de::Error::custom)
    }
}

/// The `[project]` section.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub(crate) struct ProjectManifest {
    /// The root-relative path of the entrypoint file, e.g. `main.typ`.
    entrypoint: String,
}

/// The `[packages]` section.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub(crate) struct PackagesManifest {
    /// Exact package trees whose files are stored inside the Pack.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    vendored: Vec<PackageManifest>,
    /// Exact package trees that must be externally fulfilled.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    unvendored: Vec<PackageManifest>,
}

#[derive(Default, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
struct Version1PackagesManifest {
    #[serde(default)]
    vendored: Vec<PackageManifest>,
    #[serde(default)]
    unvendored: Vec<PackageManifest>,
}

impl TryFrom<Version1PackagesManifest> for PackagesManifest {
    type Error = PackManifestError;

    fn try_from(packages: Version1PackagesManifest) -> Result<Self, Self::Error> {
        Ok(Self {
            vendored: packages.vendored,
            unvendored: packages.unvendored,
        })
    }
}

impl<'de> Deserialize<'de> for PackagesManifest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Version1PackagesManifest::deserialize(deserializer)?
            .try_into()
            .map_err(serde::de::Error::custom)
    }
}

/// One exact Package Tree declaration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub(crate) struct PackageManifest {
    spec: String,
    tree_digest: String,
    tree_identity_kind: String,
    tree_identity_schema: String,
    tree_identity_algorithm: String,
    file_count: u64,
    byte_length: u64,
}

/// One `[[fonts]]` entry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub(crate) struct FontManifest {
    /// The archive entry holding the font data, e.g. `fonts/dejavu-sans.ttf`.
    path: String,
    /// The face index inside the font file (non-zero for collections).
    #[serde(default, skip_serializing_if = "is_zero")]
    index: u32,
    /// Family names provided by this face, informational only.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    families: Vec<String>,
    /// Whether the exact container must be supplied when compiling.
    #[serde(default, skip_serializing_if = "is_false")]
    external: bool,
    /// The canonical container digest, encoded as 32 lowercase hexadecimal digits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    container_digest: Option<String>,
    /// Canonical identity kind.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    container_identity_kind: Option<String>,
    /// Canonical identity schema.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    container_identity_schema: Option<String>,
    /// Canonical identity digest algorithm.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    container_identity_algorithm: Option<String>,
    /// The exact container byte length.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    container_length: Option<u64>,
}

fn is_zero(index: &u32) -> bool {
    *index == 0
}

fn is_false(value: &bool) -> bool {
    !*value
}

/// The optional `[metadata]` section.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct PackMetadata {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    authors: Vec<String>,
}

impl ProjectManifest {
    /// The root-relative entrypoint path.
    pub fn entrypoint(&self) -> &str {
        &self.entrypoint
    }
}

impl PackagesManifest {
    /// Exact package trees stored inside the Pack.
    pub fn vendored(&self) -> &[PackageManifest] {
        &self.vendored
    }

    /// Exact package trees fulfilled outside the Pack.
    pub fn unvendored(&self) -> &[PackageManifest] {
        &self.unvendored
    }

    fn is_empty(&self) -> bool {
        self.vendored.is_empty() && self.unvendored.is_empty()
    }
}

impl PackageManifest {
    #[cfg(test)]
    pub(crate) fn new(
        spec: PackageSpec,
        tree_digest: String,
        file_count: u64,
        byte_length: u64,
    ) -> Self {
        Self {
            spec: spec.to_string(),
            tree_digest,
            tree_identity_kind: "complete-package-tree".to_owned(),
            tree_identity_schema: "typst-pack-complete-package-tree-v1".to_owned(),
            tree_identity_algorithm: "typst-hash128-0.15".to_owned(),
            file_count,
            byte_length,
        }
    }

    pub(crate) fn spec(&self) -> Result<PackageSpec, InvalidPackageSpec> {
        PackageSpec::from_str(&self.spec).map_err(|error| InvalidPackageSpec {
            spec: self.spec.clone(),
            message: error.to_string(),
        })
    }

    pub fn tree_digest(&self) -> &str {
        &self.tree_digest
    }
    pub fn tree_identity_kind(&self) -> &str {
        &self.tree_identity_kind
    }
    pub fn tree_identity_schema(&self) -> &str {
        &self.tree_identity_schema
    }
    pub fn tree_identity_algorithm(&self) -> &str {
        &self.tree_identity_algorithm
    }
    pub fn file_count(&self) -> u64 {
        self.file_count
    }
    pub fn byte_length(&self) -> u64 {
        self.byte_length
    }
}

impl std::fmt::Display for PackageManifest {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.spec)
    }
}

impl FontManifest {
    #[cfg(test)]
    pub(crate) fn with_identity_fields(
        container_digest: Option<String>,
        container_identity_kind: Option<String>,
        container_identity_schema: Option<String>,
        container_identity_algorithm: Option<String>,
    ) -> Self {
        Self {
            path: "fonts/test.ttf".to_owned(),
            index: 0,
            families: Vec::new(),
            external: false,
            container_digest,
            container_identity_kind,
            container_identity_schema,
            container_identity_algorithm,
            container_length: None,
        }
    }

    /// The archive path containing this font's bytes.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// The face index within the font data.
    pub fn index(&self) -> u32 {
        self.index
    }

    /// Informational family names declared for this face.
    #[cfg(test)]
    pub(crate) fn families(&self) -> &[String] {
        &self.families
    }

    /// Whether this face's container is externally fulfilled.
    pub fn is_external(&self) -> bool {
        self.external
    }

    pub(crate) fn container_digest(&self) -> Option<&str> {
        self.container_digest.as_deref()
    }

    pub(crate) fn container_length(&self) -> Option<u64> {
        self.container_length
    }

    pub(crate) fn container_identity_kind(&self) -> Option<&str> {
        self.container_identity_kind.as_deref()
    }

    pub(crate) fn container_identity_schema(&self) -> Option<&str> {
        self.container_identity_schema.as_deref()
    }

    pub(crate) fn container_identity_algorithm(&self) -> Option<&str> {
        self.container_identity_algorithm.as_deref()
    }
}

impl PackMetadata {
    /// Creates empty Pack metadata.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the human-readable Pack name.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the Pack description.
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Adds a Pack author.
    pub fn with_author(mut self, author: impl Into<String>) -> Self {
        self.authors.push(author.into());
        self
    }

    /// The human-readable Pack name.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// The Pack description.
    pub fn description(&self) -> Option<&str> {
        self.description.as_deref()
    }

    /// The Pack authors.
    pub fn authors(&self) -> &[String] {
        &self.authors
    }
}

/// A manifest that could not be accepted.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PackManifestError {
    #[error("failed to parse manifest: {0}")]
    Parse(#[from] toml::de::Error),
    #[error("missing or invalid `format-version`")]
    InvalidFormatVersion,
    #[error("unsupported pack format version {0} (this reader supports version {FORMAT_VERSION})")]
    UnsupportedVersion(u32),
    #[error("the {MANIFEST_PATH} manifest is not valid UTF-8: {0}")]
    NotUtf8(#[source] std::str::Utf8Error),
}

#[derive(Debug)]
pub(crate) struct InvalidPackageSpec {
    pub(crate) spec: String,
    pub(crate) message: String,
}

impl PackManifest {
    #[cfg(test)]
    pub(crate) fn new(
        entrypoint: String,
        vendored_packages: Vec<PackageManifest>,
        unvendored_packages: Vec<PackageManifest>,
        fonts: Vec<FontManifest>,
        metadata: Option<PackMetadata>,
    ) -> Self {
        Self {
            format_version: FORMAT_VERSION,
            project: ProjectManifest { entrypoint },
            packages: PackagesManifest {
                vendored: vendored_packages,
                unvendored: unvendored_packages,
            },
            fonts,
            metadata,
        }
    }

    /// The Pack format version.
    #[cfg(test)]
    pub(crate) fn format_version(&self) -> u32 {
        self.format_version
    }

    /// The project declarations.
    pub fn project(&self) -> &ProjectManifest {
        &self.project
    }

    /// The package declarations.
    pub fn packages(&self) -> &PackagesManifest {
        &self.packages
    }

    /// The embedded font declarations.
    pub fn fonts(&self) -> &[FontManifest] {
        &self.fonts
    }

    /// Optional descriptive Pack metadata.
    pub fn metadata(&self) -> Option<&PackMetadata> {
        self.metadata.as_ref()
    }

    /// Parses and validates a manifest from TOML text.
    pub fn from_toml(text: &str) -> Result<Self, PackManifestError> {
        Self::from_toml_value(toml::from_str(text)?)
    }

    pub(crate) fn from_toml_value(value: toml::Value) -> Result<Self, PackManifestError> {
        parse_manifest_value(value)
    }

    /// Serializes the manifest to TOML text.
    #[cfg(test)]
    pub fn to_toml(&self) -> String {
        toml::to_string_pretty(self).expect("manifest is always serializable")
    }

    /// Checks internal consistency of the manifest.
    fn validate(&self) -> Result<(), PackManifestError> {
        if self.format_version != FORMAT_VERSION {
            return Err(PackManifestError::UnsupportedVersion(self.format_version));
        }
        Ok(())
    }
}

fn parse_manifest_value(value: toml::Value) -> Result<PackManifest, PackManifestError> {
    let version = value
        .get("format-version")
        .and_then(toml::Value::as_integer)
        .ok_or(PackManifestError::InvalidFormatVersion)?;
    let version = u32::try_from(version).map_err(|_| PackManifestError::InvalidFormatVersion)?;
    if version != FORMAT_VERSION {
        return Err(PackManifestError::UnsupportedVersion(version));
    }
    let wire: Version1Manifest = value.try_into()?;
    let manifest = PackManifest::try_from(wire)?;
    manifest.validate()?;
    Ok(manifest)
}