Skip to main content

tauri_plugin_compmd/
lib.rs

1//! `tauri-plugin-compmd`: the Tauri adapter of [CompMD](https://compmd.dev/)'s hosting (docs/tauri-plugin.md,
2//! docs/hosting.md).
3//!
4//! What every host does is shared: the configuration, the bundle `@compmd/vite` builds from the page's own
5//! `@compmd/sandbox`, the pack store and the serving contract (`compmd-host`). The plugin does the four things only
6//! Tauri can: it embeds the bundle in the app, serves it on the scheme the bundle was built for, gives the page the
7//! origin, and gives the store a folder.
8//!
9//! The bundle is written by `@compmd/vite` (`compmd({ out: "src-tauri/compmd", source: "compmd://localhost/" })`);
10//! the app's `build.rs` embeds it, with the `build` feature:
11//!
12//! ```no_run
13//! # #[cfg(feature = "build")]
14//! tauri_plugin_compmd::build::bundle("compmd");
15//! ```
16//!
17//! and its `main` passes it to the plugin:
18//!
19//! ```ignore
20//! tauri::Builder::default().plugin(tauri_plugin_compmd::init(tauri_plugin_compmd::include_bundle!()))
21//! ```
22//!
23//! The page then takes everything from its own bundle and the origin from the plugin, and passes nothing:
24//!
25//! ```js
26//! import { sandbox } from "virtual:compmd";
27//! const view = createSandbox({ ...sandbox, page: "host" }).open(container, { components });
28//! ```
29
30#[cfg(feature = "build")]
31pub mod build;
32#[cfg(feature = "build")]
33mod build_error;
34mod compmd;
35mod origin;
36mod scheme;
37
38use std::path::PathBuf;
39use std::sync::Arc;
40
41pub use compmd::Compmd;
42/// The shared layers of hosting: the bundle, the store and the serving contract.
43pub use compmd_host;
44use compmd_host::{Bundle, FolderStore, NoStore, Store};
45use tauri::plugin::{Builder, TauriPlugin};
46use tauri::{Manager, Runtime};
47
48#[cfg(feature = "build")]
49pub use build_error::BuildError;
50
51/// The bundle `build::bundle` embedded in the app, or `None` when the build found none (with a warning then): the
52/// plugin then serves nothing, and the page reports that its frames didn't load.
53///
54/// ```ignore
55/// tauri::Builder::default().plugin(tauri_plugin_compmd::init(tauri_plugin_compmd::include_bundle!()))
56/// ```
57#[macro_export]
58macro_rules! include_bundle {
59    () => {
60        $crate::embedded(include!(concat!(env!("OUT_DIR"), "/compmd_bundle.rs")))
61    };
62}
63
64/// The bundle of the files `build::bundle` embedded, for [`include_bundle!`]; none when there are none.
65///
66/// # Panics
67///
68/// When the embedded files aren't a bundle that can be served (its manifest missing, of another format, or naming a
69/// path that isn't one), saying why: a mistake in the app's build, as [`init`]'s others are (audit B13).
70#[doc(hidden)]
71#[must_use]
72pub fn embedded(files: Option<&'static [(&'static str, &'static [u8])]>) -> Option<Bundle> {
73    files.map(|files| {
74        Bundle::embedded(files)
75            .unwrap_or_else(|error| panic!("the embedded bundle can't be served: {error}"))
76    })
77}
78
79/// The plugin, serving `bundle` on the scheme its manifest names (`compmd`), with the origin given to the app's pages
80/// and the pack store in the app's data folder.
81///
82/// # Panics
83///
84/// When the bundle's scheme isn't a scheme's name, or it was built without one (`source`): mistakes in the app's
85/// build, which `build::bundle` refuses already.
86///
87/// # Example
88///
89/// ```
90/// # use compmd_host::Bundle;
91/// let bundle = Bundle::from_files([(
92///     "manifest.json",
93///     br#"{"format": 1, "frames": {"hash": "1df336e75685de8c"}, "source": "compmd://localhost/"}"#.to_vec(),
94/// )])?;
95/// let app = tauri::Builder::<tauri::Wry>::default().plugin(tauri_plugin_compmd::init(bundle));
96/// # drop(app);
97/// # Ok::<(), compmd_host::BundleError>(())
98/// ```
99#[must_use]
100pub fn init<R: Runtime>(bundle: impl Into<Option<Bundle>>) -> TauriPlugin<R> {
101    let bundle = bundle.into();
102    let scheme = bundle.as_ref().map(|bundle| {
103        let scheme = bundle.manifest().scheme();
104        let scheme = scheme.unwrap_or_else(|| panic!("{}", BUILT_WITHOUT_SOURCE));
105        assert!(
106            origin::is_scheme(scheme),
107            "`{scheme}` isn't a scheme's name"
108        );
109        scheme.to_owned()
110    });
111    let origin = scheme.as_deref().map(origin::origin_of);
112    let mut plugin = Builder::new("compmd");
113    if let (Some(scheme), Some(origin)) = (&scheme, &origin) {
114        plugin = plugin
115            .js_init_script(origin::init_script(origin))
116            .register_uri_scheme_protocol(scheme.clone(), scheme::serve);
117    }
118    plugin
119        .setup(move |app, _api| {
120            let store = store_in(app.path().app_data_dir().ok());
121            app.manage(Compmd::new(bundle, origin, store));
122            Ok(())
123        })
124        .build()
125}
126
127/// The pack store in the app's data folder, `compmd/packs/` there (docs/tauri-plugin.md, decision 11); none when the
128/// platform gives the app no data folder.
129fn store_in(data: Option<PathBuf>) -> Arc<dyn Store> {
130    data.map_or_else(
131        || Arc::new(NoStore) as Arc<dyn Store>,
132        |data| Arc::new(FolderStore::new(data.join("compmd").join("packs"))),
133    )
134}
135
136/// Why a bundle built for an http origin can't be served on a scheme.
137pub(crate) const BUILT_WITHOUT_SOURCE: &str = "the bundle was built without a `source`, so it names no scheme: build it with the scheme it is served on, `compmd({ out, source: \"compmd://localhost/\" })`";
138
139/// What the plugin gives Rust code of the app.
140pub trait CompmdExt<R: Runtime> {
141    /// The bundle the app serves, its origin and the pack store.
142    fn compmd(&self) -> &Compmd;
143}
144
145impl<R: Runtime, T: Manager<R>> CompmdExt<R> for T {
146    fn compmd(&self) -> &Compmd {
147        self.state::<Compmd>().inner()
148    }
149}
150
151#[cfg(test)]
152mod tests;