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#[doc(hidden)]
66#[must_use]
67pub fn embedded(files: Option<&'static [(&'static str, &'static [u8])]>) -> Option<Bundle> {
68 files.and_then(|files| Bundle::embedded(files).ok())
69}
70
71/// The plugin, serving `bundle` on the scheme its manifest names (`compmd`), with the origin given to the app's pages
72/// and the pack store in the app's data folder.
73///
74/// # Panics
75///
76/// When the bundle's scheme isn't a scheme's name, or it was built without one (`source`): mistakes in the app's
77/// build, which `build::bundle` refuses already.
78///
79/// # Example
80///
81/// ```
82/// # use compmd_host::Bundle;
83/// let bundle = Bundle::from_files([(
84/// "manifest.json",
85/// br#"{"format": 1, "frames": {"hash": "1df336e75685de8c"}, "source": "compmd://localhost/"}"#.to_vec(),
86/// )])?;
87/// let app = tauri::Builder::<tauri::Wry>::default().plugin(tauri_plugin_compmd::init(bundle));
88/// # drop(app);
89/// # Ok::<(), compmd_host::BundleError>(())
90/// ```
91#[must_use]
92pub fn init<R: Runtime>(bundle: impl Into<Option<Bundle>>) -> TauriPlugin<R> {
93 let bundle = bundle.into();
94 let scheme = bundle.as_ref().map(|bundle| {
95 let scheme = bundle.manifest().scheme();
96 let scheme = scheme.unwrap_or_else(|| panic!("{}", BUILT_WITHOUT_SOURCE));
97 assert!(
98 origin::is_scheme(scheme),
99 "`{scheme}` isn't a scheme's name"
100 );
101 scheme.to_owned()
102 });
103 let origin = scheme.as_deref().map(origin::origin_of);
104 let mut plugin = Builder::new("compmd");
105 if let (Some(scheme), Some(origin)) = (&scheme, &origin) {
106 plugin = plugin
107 .js_init_script(origin::init_script(origin))
108 .register_uri_scheme_protocol(scheme.clone(), scheme::serve);
109 }
110 plugin
111 .setup(move |app, _api| {
112 let store = store_in(app.path().app_data_dir().ok());
113 app.manage(Compmd::new(bundle, origin, store));
114 Ok(())
115 })
116 .build()
117}
118
119/// The pack store in the app's data folder, `compmd/packs/` there (docs/tauri-plugin.md, decision 11); none when the
120/// platform gives the app no data folder.
121fn store_in(data: Option<PathBuf>) -> Arc<dyn Store> {
122 data.map_or_else(
123 || Arc::new(NoStore) as Arc<dyn Store>,
124 |data| Arc::new(FolderStore::new(data.join("compmd").join("packs"))),
125 )
126}
127
128/// Why a bundle built for an http origin can't be served on a scheme.
129pub(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/\" })`";
130
131/// What the plugin gives Rust code of the app.
132pub trait CompmdExt<R: Runtime> {
133 /// The bundle the app serves, its origin and the pack store.
134 fn compmd(&self) -> &Compmd;
135}
136
137impl<R: Runtime, T: Manager<R>> CompmdExt<R> for T {
138 fn compmd(&self) -> &Compmd {
139 self.state::<Compmd>().inner()
140 }
141}
142
143#[cfg(test)]
144mod tests;