Skip to main content

compmd_host/
packs.rs

1//! The processor's packs over the bundle and the store ([hosting], decision 7): a host that processes documents in Rust
2//! resolves imports from exactly the files the frames load.
3//!
4//! [hosting]: https://github.com/comp-markdown/compmd/blob/main/docs/hosting.md
5
6use std::sync::Arc;
7
8use compmd::Ambient;
9use compmd::host::{Packs, Release};
10use compmd::policy::Policy;
11use compmd_pack::{PackName, Place};
12use serde::Deserialize;
13
14use crate::bundle::Bundle;
15use crate::manifest_error::ManifestError;
16use crate::store::Store;
17
18/// The bundle's packs, then the store's, as `compmd::host::Packs`, with the policy and the ambient packs the bundle's
19/// configuration made, so a document processed in Rust is held to what the page's path holds it to ([hosting],
20/// decision 7). It shares the bundle and the store, which the host keeps, so the processor, which keeps its packs while
21/// it processes, can be given it.
22///
23/// ```
24/// # use std::sync::Arc;
25/// # use compmd::{ParseOptions, Processor};
26/// # use compmd_host::{Bundle, HostPacks, NoStore};
27/// # let bundle = Bundle::from_files([("manifest.json", br#"{"format": 1, "frames": {"hash": "1df336e75685de8c"}}"#.to_vec())])?;
28/// let packs = HostPacks::new(Arc::new(bundle), Arc::new(NoStore));
29/// let (policy, ambient) = (packs.policy()?, packs.ambient());
30/// let resolved = Processor::new("a.comp.md", "# A\n")
31///     .parse(&ParseOptions::default())
32///     .resolve_with((), packs, &ambient, &policy);
33/// # drop(resolved);
34/// # Ok::<(), Box<dyn std::error::Error>>(())
35/// ```
36///
37/// [hosting]: https://github.com/comp-markdown/compmd/blob/main/docs/hosting.md
38#[derive(Clone)]
39pub struct HostPacks {
40    bundle: Arc<Bundle>,
41    store: Arc<dyn Store>,
42}
43
44impl HostPacks {
45    /// The packs of `bundle`, then of `store`.
46    #[must_use]
47    pub fn new(bundle: Arc<Bundle>, store: Arc<dyn Store>) -> Self {
48        Self { bundle, store }
49    }
50
51    /// The processor's policy the bundle's configuration made (its `deny`, `imports`, `refused` and the packs' trust):
52    /// the default policy when the manifest has none.
53    ///
54    /// # Errors
55    ///
56    /// [`ManifestError::Policy`] when the manifest's `policy` isn't the processor's.
57    pub fn policy(&self) -> Result<Policy, ManifestError> {
58        self.bundle.manifest().policy.as_ref().map_or_else(
59            || Ok(Policy::default()),
60            |policy| {
61                Policy::deserialize(policy)
62                    .map_err(|error| ManifestError::Policy(error.to_string()))
63            },
64        )
65    }
66
67    /// The packs every document gets without importing them, as the bundle's configuration names them; their uses
68    /// aren't reported, as on the page's path.
69    #[must_use]
70    pub fn ambient(&self) -> Ambient {
71        Ambient {
72            packs: self.bundle.manifest().ambient.clone(),
73            report: false,
74        }
75    }
76}
77
78impl Packs for HostPacks {
79    fn releases(&self, pack: &PackName) -> Vec<Release> {
80        let bundled = self
81            .bundle
82            .manifest()
83            .packs
84            .iter()
85            .filter(|bundled| bundled.release.pack == *pack)
86            .map(|bundled| Release {
87                version: bundled.release.version.clone(),
88                integrity: bundled.integrity.clone(),
89                broken: None,
90            });
91        let mut releases: Vec<Release> = bundled.collect();
92        for stored in self.store.releases(pack) {
93            if !releases
94                .iter()
95                .any(|release| release.version == stored.release.version)
96            {
97                releases.push(Release {
98                    version: stored.release.version,
99                    integrity: Some(stored.integrity),
100                    broken: None,
101                });
102            }
103        }
104        releases
105    }
106
107    fn pack_file(&self, place: &Place) -> Option<String> {
108        let bytes = self.bundle.pack_file_or(self.store.as_ref(), place)?;
109        String::from_utf8(bytes).ok()
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use compmd_pack::ReleaseId;
116
117    use super::*;
118    use crate::bundle::tests::{bundle, place};
119    use crate::no_store::NoStore;
120    use crate::stored_release::StoredRelease;
121
122    /// A store holding `@kit/mermaid` 1.2.0 (the bundle's too) and 1.3.0, and a binary file.
123    struct Kept;
124
125    impl Store for Kept {
126        fn releases(&self, pack: &PackName) -> Vec<StoredRelease> {
127            if *pack != "@kit/mermaid" {
128                return Vec::new();
129            }
130            [2, 3]
131                .into_iter()
132                .map(|minor| StoredRelease {
133                    release: format!("@kit/mermaid@1.{minor}.0")
134                        .parse::<ReleaseId>()
135                        .expect("a release"),
136                    integrity: format!("sha512-{minor}").parse().expect("an integrity"),
137                })
138                .collect()
139        }
140
141        fn file(&self, place: &Place) -> Option<Vec<u8>> {
142            match place.to_string().as_str() {
143                "@kit/mermaid@1.3.0/package.json" => Some(b"{}".to_vec()),
144                "@kit/mermaid@1.3.0/logo.png" => Some(vec![0xff, 0xfe]),
145                _ => None,
146            }
147        }
148    }
149
150    #[test]
151    fn the_bundles_release_comes_first_and_the_stores_others_after() {
152        let packs = HostPacks::new(Arc::new(bundle()), Arc::new(Kept));
153        let releases = packs.releases(&"@kit/mermaid".parse().expect("a name"));
154        let versions: Vec<String> = releases
155            .iter()
156            .map(|release| release.version.to_string())
157            .collect();
158        assert_eq!(versions, ["1.2.0", "1.3.0"]);
159        let integrity = |text: &str| Some(text.parse().expect("an integrity"));
160        assert_eq!(
161            releases[0].integrity,
162            integrity("sha512-abc"),
163            "the bundle's integrity"
164        );
165        assert_eq!(releases[1].integrity, integrity("sha512-3"));
166        assert_eq!(packs.releases(&"@kit/none".parse().expect("a name")), []);
167    }
168
169    /// A bundle holding `@kit/notes` (a `note` component) and `@kit/old`, whose configuration makes `@kit/notes` ambient
170    /// and denies `@kit/old`, as `@compmd/vite` writes it.
171    fn configured() -> HostPacks {
172        let manifest = br#"{"format": 1, "frames": {"hash": "1df336e75685de8c"},
173            "packs": [{"pack": "@kit/notes", "version": "1.0.0"}, {"pack": "@kit/old", "version": "1.0.0"}],
174            "policy": {"deny": [{"pack": "@kit/old", "reason": "a flaw found in 1.x"}]},
175            "ambient": ["@kit/notes"]}"#;
176        let pack = |name: &str| {
177            [
178                (
179                    format!("packs/{name}@1.0.0/package.json"),
180                    format!(r#"{{"name": "{name}", "version": "1.0.0"}}"#).into_bytes(),
181                ),
182                (
183                    format!("packs/{name}@1.0.0/index.comp.md"),
184                    b"---\nmd:\n  export:\n    names: \"*\"\n---\n\n```compmd component=note\n---\nA note.\n```\n".to_vec(),
185                ),
186            ]
187        };
188        let files = [("manifest.json".to_owned(), manifest.to_vec())]
189            .into_iter()
190            .chain(pack("@kit/notes"))
191            .chain(pack("@kit/old"));
192        HostPacks::new(
193            Arc::new(Bundle::from_files(files).expect("a bundle")),
194            Arc::new(NoStore),
195        )
196    }
197
198    /// The diagnostics of `text` processed in Rust with the bundle's packs, policy and ambient packs.
199    fn diagnostics(text: &str) -> Vec<String> {
200        let packs = configured();
201        let (policy, ambient) = (packs.policy().expect("a policy"), packs.ambient());
202        compmd::Processor::new("a.comp.md", text)
203            .parse(&compmd::ParseOptions::default())
204            .resolve_with((), packs, &ambient, &policy)
205            .diagnostics()
206            .iter()
207            .map(|diagnostic| format!("{} {}", diagnostic.code, diagnostic.message))
208            .collect()
209    }
210
211    #[test]
212    fn processing_in_rust_holds_a_document_to_the_bundles_policy() {
213        let denied = diagnostics(
214            "---\nmd:\n  import:\n    - from: \"@kit/old@1\"\n      names: \"*\"\n---\n",
215        );
216        assert_eq!(
217            denied,
218            ["F026 `@kit/old@1.0.0` is denied here: a flaw found in 1.x; the import is dropped"]
219        );
220    }
221
222    #[test]
223    fn processing_in_rust_gives_a_document_the_bundles_ambient_packs() {
224        assert_eq!(diagnostics(":: note[A note]\n"), Vec::<String>::new());
225        assert_eq!(
226            configured().ambient().packs,
227            ["@kit/notes".parse::<PackName>().expect("a name")]
228        );
229    }
230
231    #[test]
232    fn a_bundle_without_a_policy_gets_the_default_and_one_the_processor_cant_read_is_an_error() {
233        let packs = HostPacks::new(Arc::new(bundle()), Arc::new(NoStore));
234        assert_eq!(packs.policy(), Ok(Policy::default()));
235        assert_eq!(packs.ambient(), Ambient::default());
236        let manifest =
237            br#"{"format": 1, "frames": {"hash": "1df336e75685de8c"}, "policy": {"imports": "some"}}"#;
238        let unreadable = HostPacks::new(
239            Arc::new(
240                Bundle::from_files([("manifest.json".to_owned(), manifest.to_vec())])
241                    .expect("a bundle"),
242            ),
243            Arc::new(NoStore),
244        );
245        assert!(
246            matches!(unreadable.policy(), Err(ManifestError::Policy(message)) if message.contains("some"))
247        );
248    }
249
250    #[test]
251    fn a_file_is_read_from_the_bundle_or_the_store_as_text() {
252        let bundle = Arc::new(bundle());
253        let packs = HostPacks::new(Arc::clone(&bundle), Arc::new(Kept));
254        assert_eq!(
255            packs
256                .pack_file(&place("@kit/mermaid@1.2.0/package.json"))
257                .as_deref(),
258            Some(r#"{"name": "@kit/mermaid"}"#)
259        );
260        assert_eq!(
261            packs
262                .pack_file(&place("@kit/mermaid@1.3.0/package.json"))
263                .as_deref(),
264            Some("{}")
265        );
266        assert_eq!(
267            packs.pack_file(&place("@kit/mermaid@1.3.0/logo.png")),
268            None,
269            "not text"
270        );
271        assert_eq!(
272            HostPacks::new(bundle, Arc::new(NoStore))
273                .pack_file(&place("@kit/mermaid@1.3.0/package.json")),
274            None
275        );
276    }
277}