Skip to main content

devpage_core/
extensions.rs

1//! Extension contracts and captured state; the executable installs the native loader.
2mod browser;
3use crate::folder::ServedFolder;
4use anyhow::{Result, anyhow, bail};
5use browser::Browser;
6use serde::{Deserialize, Serialize};
7use serde_json::{Value, json};
8use sha2::{Digest, Sha256};
9use std::{
10    collections::BTreeMap,
11    path::{Path, PathBuf},
12    sync::{Arc, Mutex, OnceLock},
13};
14/// An extension's package, loaded: what devpage asks, in JSON, to read its
15/// input and show its files.
16pub trait Package: Send + Sync {
17    /// The package's reply to `request`, a JSON object whose `op` names what is
18    /// asked: `create`, `prepare`, `view`, `augment`, `embed`, `targets` or
19    /// `route`.
20    fn invoke(&self, request: Value) -> Result<Value>;
21}
22/// What loads an extension's package from its bundle; the executable installs
23/// the native one.
24pub trait Loader: Send + Sync {
25    /// The package bundled at `path`.
26    fn load(&self, path: &Path) -> Result<Arc<dyn Package>>;
27}
28/// The loader the executable installed; until it does, no extension can be
29/// configured.
30static LOADER: OnceLock<Arc<dyn Loader>> = OnceLock::new();
31/// Installs `loader` as the one every package is loaded with; a second call is
32/// ignored.
33pub fn install_loader(loader: Arc<dyn Loader>) {
34    let _ = LOADER.set(loader);
35}
36/// Every configured document's extensions, by the document's file.
37static INSTANCES: OnceLock<Mutex<BTreeMap<PathBuf, Vec<Binding>>>> = OnceLock::new();
38/// Every configured document's extensions, by the document's file — empty at
39/// first.
40fn instances() -> &'static Mutex<BTreeMap<PathBuf, Vec<Binding>>> {
41    INSTANCES.get_or_init(Default::default)
42}
43/// An extension as a document's `extensions:` names it: its package and what it
44/// is configured with.
45#[derive(Debug, Deserialize, Serialize)]
46#[serde(deny_unknown_fields)]
47pub struct Config {
48    /// The package's bundle; left out only for a system extension such as
49    /// [`code`](crate::code).
50    pub package: Option<String>,
51    /// What the package is created with, as written under `config:`; null when
52    /// left out.
53    #[serde(default)]
54    pub config: serde_yaml::Value,
55}
56/// An extension bound to a document: its package, the input it reads and what
57/// it last prepared from it. Clones share one state; a
58/// [`snapshot`](Self::snapshot) does not.
59#[derive(Clone)]
60pub struct Binding(Arc<Mutex<State>>);
61impl std::fmt::Debug for Binding {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.write_str("ExtensionBinding")
64    }
65}
66/// What a binding holds: its package, how it was configured and what it last
67/// prepared.
68#[derive(Clone)]
69struct State {
70    /// The extension's name under the document's `extensions:`.
71    id: String,
72    /// The document's whole `extensions:`, as JSON — what tells a changed
73    /// configuration from the bound one.
74    configuration: String,
75    /// The instance's id: the first 16 hex digits of the SHA-256 of the
76    /// document's path, `id` and `configuration`.
77    owner: String,
78    /// The package, loaded by the installed [`Loader`]; each request names
79    /// this binding by `owner`.
80    package: Arc<dyn Package>,
81    /// The served folder its input and the files it shows must lie in.
82    scope: ServedFolder,
83    /// The file or folder it reads, as the package's `create` reply names it.
84    input: PathBuf,
85    /// The package's reply to `create`: the suffixes it owns, its input and the
86    /// suffixes read there, its grammar, widgets and styles.
87    descriptor: Value,
88    /// The modules, widgets and stylesheets the package ships for the browser,
89    /// compiled.
90    browser: Arc<Browser>,
91    /// What the package named its last preparation — empty before the first.
92    revision: String,
93    /// Why the last preparation failed — `None` when it didn't, or when the
94    /// reply only lacked a revision. While set, every call fails.
95    error: Option<String>,
96    /// The input last prepared from: each file's contents, by its name in the
97    /// served folder.
98    sources: BTreeMap<String, String>,
99}
100impl Binding {
101    /// The address the binding of `s` answers under:
102    /// `<mount>/__devpage/extensions/<owner>/<id>/`.
103    fn base(s: &State) -> String {
104        format!(
105            "{}/__devpage/extensions/{}/{}/",
106            s.scope.mount(),
107            s.owner,
108            s.id
109        )
110    }
111    /// The address of each of the package's widgets' modules, by widget name.
112    pub fn widget_urls(&self) -> BTreeMap<String, String> {
113        let s = self.0.lock().unwrap();
114        s.browser.widgets(&Self::base(&s))
115    }
116    /// The addresses of the package's stylesheets.
117    pub fn style_urls(&self) -> Vec<String> {
118        let s = self.0.lock().unwrap();
119        s.browser.styles(&Self::base(&s))
120    }
121    /// The package's view of `file`, a file it owns: its `layout`, `title` and
122    /// `content`.
123    pub fn view(&self, file: &Path) -> Result<Value> {
124        let s = self.0.lock().unwrap();
125        let path = s
126            .scope
127            .name(file)
128            .ok_or_else(|| anyhow!("View outside served folder"))?;
129        drop(s);
130        self.call("view", json!({"path":path}))
131    }
132
133    /// Pin this render to its prepared revision while the watcher prepares the next.
134    pub fn snapshot(&self) -> Self {
135        Self(Arc::new(Mutex::new(self.0.lock().unwrap().clone())))
136    }
137    /// The package's reply to `op`, asked with `extra` and the instance, its
138    /// base address and revision. An error while the last preparation failed.
139    fn call(&self, op: &str, extra: Value) -> Result<Value> {
140        let s = self.0.lock().unwrap();
141        if let Some(error) = &s.error {
142            bail!("Extension preparation failed: {error}");
143        }
144        let mut request = extra;
145        request["op"] = op.into();
146        request["instance"] = s.owner.clone().into();
147        request["base"] = format!(
148            "{}/__devpage/extensions/{}/{}/",
149            s.scope.mount(),
150            s.owner,
151            s.id
152        )
153        .into();
154        request["revision"] = s.revision.clone().into();
155        s.package.invoke(request)
156    }
157    /// The file or folder the extension reads.
158    pub fn input(&self) -> PathBuf {
159        self.0.lock().unwrap().input.clone()
160    }
161    /// Whether `file` is one the extension shows: its suffix is one the package
162    /// declared and, when `file` is absolute, it lies in the input.
163    pub fn owns(&self, file: &Path) -> bool {
164        let s = self.0.lock().unwrap();
165        if file.is_absolute() && !file.starts_with(&s.input) {
166            return false;
167        }
168        let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");
169        s.descriptor["file_extensions"]
170            .as_array()
171            .is_some_and(|a| a.iter().any(|v| v.as_str() == Some(ext)))
172    }
173    /// Whether a new revision was prepared: the input is read again, and the
174    /// package prepares from it unless it is unchanged, the last preparation
175    /// succeeded and a revision is held. A failure to read or prepare is kept,
176    /// and fails every call until a preparation succeeds; a reply without a
177    /// revision fails only this preparation.
178    pub fn prepare(&self) -> Result<bool> {
179        let mut s = self.0.lock().unwrap();
180        let mut sources = BTreeMap::new();
181        fn read(
182            scope: &ServedFolder,
183            p: &Path,
184            files: &mut BTreeMap<String, String>,
185            extensions: &[Value],
186        ) -> Result<()> {
187            if std::fs::symlink_metadata(p)?.file_type().is_symlink() {
188                bail!("Symlinked extension input {}", p.display());
189            }
190            let canonical = p.canonicalize()?;
191            if !canonical.starts_with(scope.path()) {
192                bail!("Extension input outside served folder");
193            }
194            if p.is_dir() {
195                for entry in std::fs::read_dir(p)? {
196                    let entry = entry?;
197                    if !entry.file_name().to_string_lossy().starts_with('.') {
198                        read(scope, &entry.path(), files, extensions)?;
199                    }
200                }
201            } else if p
202                .extension()
203                .and_then(|e| e.to_str())
204                .is_some_and(|ext| extensions.iter().any(|v| v.as_str() == Some(ext)))
205            {
206                files.insert(
207                    scope
208                        .name(p)
209                        .ok_or_else(|| anyhow!("Input outside served folder"))?,
210                    std::fs::read_to_string(p)?,
211                );
212            }
213            Ok(())
214        }
215        let extensions = s.descriptor["input_extensions"]
216            .as_array()
217            .ok_or_else(|| anyhow!("Extension must declare input_extensions"))?;
218        if let Err(error) = read(&s.scope, &s.input, &mut sources, extensions) {
219            s.error = Some(error.to_string());
220            return Err(error);
221        }
222        if s.error.is_none() && s.sources == sources && !s.revision.is_empty() {
223            return Ok(false);
224        }
225        let reply = match s
226            .package
227            .invoke(json!({"op":"prepare","instance":s.owner,"sources":sources}))
228        {
229            Ok(reply) => reply,
230            Err(error) => {
231                s.error = Some(format!("{error:#}"));
232                return Err(error);
233            }
234        };
235        s.revision = reply["revision"]
236            .as_str()
237            .ok_or_else(|| anyhow!("Extension preparation omitted revision"))?
238            .into();
239        s.sources = sources;
240        s.error = None;
241        Ok(true)
242    }
243    /// The syntax definition the package highlights its language with — `None`
244    /// when it brings none.
245    pub fn grammar(&self) -> Option<String> {
246        self.0.lock().unwrap().descriptor["grammar"]
247            .as_str()
248            .map(String::from)
249    }
250    /// `source`, the page at `file`, as the package augments it — unchanged
251    /// when the reply has no `source`.
252    pub fn transform(&self, file: &Path, source: &str) -> Result<String> {
253        let s = self.0.lock().unwrap();
254        let path = s
255            .scope
256            .name(file)
257            .ok_or_else(|| anyhow!("Page outside served folder"))?;
258        drop(s);
259        let reply = self.call("augment", json!({"path":path,"source":source}))?;
260        Ok(reply["source"].as_str().unwrap_or(source).into())
261    }
262    /// The HTML the package shows `target` as in the page at `file`, with
263    /// `label`; `identity` is its place among the page's `src` targets.
264    pub fn embed(&self, file: &Path, target: &str, label: &str, identity: usize) -> Result<String> {
265        let s = self.0.lock().unwrap();
266        let path = s
267            .scope
268            .name(file)
269            .ok_or_else(|| anyhow!("Page outside served folder"))?;
270        drop(s);
271        Ok(self.call(
272            "embed",
273            json!({"page":path,"target":target,"label":label,"identity":identity}),
274        )?["html"]
275            .as_str()
276            .ok_or_else(|| anyhow!("Missing embed HTML"))?
277            .into())
278    }
279    /// The ids a link may point at inside `file`, a file the extension owns.
280    pub fn ids(&self, file: &Path) -> Result<Vec<String>> {
281        let s = self.0.lock().unwrap();
282        let path = s
283            .scope
284            .name(file)
285            .ok_or_else(|| anyhow!("Target outside served folder"))?;
286        drop(s);
287        Ok(self.call("targets", json!({"path":path}))?["ids"]
288            .as_array()
289            .into_iter()
290            .flatten()
291            .filter_map(|v| v.as_str().map(String::from))
292            .collect())
293    }
294}
295/// Binds the extensions `configs` to the document at `doc`, each package loaded
296/// from its bundle under `base`, and prepares each; no `configs` unbinds it. A
297/// configuration already bound in `scope` is kept as it is.
298pub fn configure(
299    doc: &Path,
300    base: &Path,
301    scope: &ServedFolder,
302    configs: BTreeMap<String, Config>,
303) -> Result<()> {
304    let mut guard = instances().lock().unwrap();
305    if configs.is_empty() {
306        guard.remove(doc);
307        return Ok(());
308    }
309    let configuration = serde_json::to_string(&configs)?;
310    if guard.get(doc).is_some_and(|bindings| {
311        bindings.iter().all(|b| {
312            let s = b.0.lock().unwrap();
313            s.configuration == configuration && s.scope == *scope
314        })
315    }) {
316        return Ok(());
317    }
318    let loader = LOADER
319        .get()
320        .ok_or_else(|| anyhow!("Native extension loader unavailable"))?;
321    let mut bindings = vec![];
322    let mut claims: std::collections::BTreeSet<String> = ["md", "yml", "yaml", "design"]
323        .into_iter()
324        .map(String::from)
325        .collect();
326    for (id, config) in configs {
327        let Some(path) = &config.package else {
328            bail!("extensions: {id}: package is required — {id} is not a system extension");
329        };
330        let package = loader
331            .load(&base.join(path))
332            .map_err(|e| anyhow!("Extension {id}: {e:#}"))?;
333        let owner = format!(
334            "{:x}",
335            Sha256::digest(format!("{}:{id}:{configuration}", doc.display()))
336        )[..16]
337            .to_string();
338        let descriptor = package
339            .invoke(json!({"op":"create","instance":owner,"id":id,"config":config.config}))?;
340        for suffix in descriptor["file_extensions"]
341            .as_array()
342            .ok_or_else(|| anyhow!("Extension {id} file_extensions missing"))?
343        {
344            let suffix = suffix
345                .as_str()
346                .filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric()))
347                .ok_or_else(|| anyhow!("Extension {id} invalid file suffix"))?;
348            if !claims.insert(suffix.into()) {
349                bail!("Extension {id} file format {suffix} is already claimed");
350            }
351        }
352        if let Some(grammar) = descriptor["grammar"].as_str() {
353            let syntax = syntect::parsing::SyntaxDefinition::load_from_str(grammar, true, None)
354                .map_err(|e| anyhow!("Extension {id} grammar: {e}"))?;
355            if syntax
356                .file_extensions
357                .iter()
358                .any(|s| crate::highlight::builtin_language(s))
359            {
360                bail!("Extension {id} cannot replace a built-in language");
361            }
362        }
363        let input = base.join(
364            descriptor["input"]
365                .as_str()
366                .ok_or_else(|| anyhow!("Extension input missing"))?,
367        );
368        if !input.canonicalize()?.starts_with(scope.path()) {
369            bail!("Extension {id} input outside served folder");
370        }
371        let browser = Browser::new(
372            &descriptor,
373            &format!("{}/__devpage/extensions/{owner}/{id}/", scope.mount()),
374        )?;
375        let binding = Binding(Arc::new(Mutex::new(State {
376            id,
377            configuration: configuration.clone(),
378            owner,
379            package,
380            scope: scope.clone(),
381            input,
382            descriptor,
383            browser: Arc::new(browser),
384            revision: String::new(),
385            error: None,
386            sources: BTreeMap::new(),
387        })));
388        binding.prepare()?;
389        bindings.push(binding);
390    }
391    guard.insert(doc.to_path_buf(), bindings);
392    Ok(())
393}
394/// The extensions bound to the document at `doc` — none when it has none.
395pub fn for_document(doc: &Path) -> Vec<Binding> {
396    instances()
397        .lock()
398        .unwrap()
399        .get(doc)
400        .cloned()
401        .unwrap_or_default()
402}
403/// The input of every extension bound in `scope`, for the watcher to watch.
404pub fn input_roots(scope: &ServedFolder) -> Vec<PathBuf> {
405    instances()
406        .lock()
407        .unwrap()
408        .values()
409        .flatten()
410        .filter(|b| b.0.lock().unwrap().scope == *scope)
411        .map(Binding::input)
412        .collect()
413}
414/// Whether an extension in `scope` prepared anew after `files` changed: each
415/// whose input holds one of them, or lies in one, prepares again. A failed
416/// preparation counts as a change.
417pub fn changed(scope: &ServedFolder, files: &[PathBuf]) -> bool {
418    let all: Vec<_> = instances()
419        .lock()
420        .unwrap()
421        .values()
422        .flatten()
423        .filter(|b| b.0.lock().unwrap().scope == *scope)
424        .cloned()
425        .collect();
426    let mut changed = false;
427    for b in all {
428        let input = b.input();
429        if files
430            .iter()
431            .any(|p| p.starts_with(&input) || input.starts_with(p))
432        {
433            changed |= b.prepare().unwrap_or(true);
434        }
435    }
436    changed
437}
438/// The extensions of the document that owns `file` in `folder` — the entry
439/// document's when none does.
440pub fn for_file(file: &Path, folder: &crate::folder::Folder) -> Vec<Binding> {
441    let path = folder
442        .owner(file)
443        .and_then(|o| o.document.ok())
444        .map(|d| d.path())
445        .unwrap_or_else(|| folder.entry().path());
446    for_document(&path)
447}
448/// The reply to `path` when it is an extension's address in `scope`: a browser
449/// file the package ships, or else what the package routes it to. `None` when
450/// it is no extension's.
451pub fn route(path: &str, scope: &ServedFolder) -> Option<Result<Value>> {
452    let suffix = path
453        .trim_start_matches('/')
454        .strip_prefix("__devpage/extensions/")?;
455    let (owner, tail) = suffix.split_once('/')?;
456    let (id, tail) = tail.split_once('/')?;
457    let all: Vec<_> = instances()
458        .lock()
459        .unwrap()
460        .values()
461        .flatten()
462        .cloned()
463        .collect();
464    all.into_iter()
465        .find(|b| {
466            let s = b.0.lock().unwrap();
467            s.owner == owner && s.id == id && s.scope == *scope
468        })
469        .map(|b| {
470            let response = {
471                let s = b.0.lock().unwrap();
472                s.browser.response(tail)
473            };
474            response.map_or_else(|| b.call("route", json!({"path":tail})), Ok)
475        })
476}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481    struct Toy;
482    impl Loader for Toy {
483        fn load(&self, _: &Path) -> Result<Arc<dyn Package>> {
484            Ok(Arc::new(Toy))
485        }
486    }
487    impl Package for Toy {
488        fn invoke(&self, r: Value) -> Result<Value> {
489            Ok(match r["op"].as_str().unwrap() {
490                "create" => {
491                    json!({"input":r["config"]["input"],"input_extensions":["toy","md"],"file_extensions":["toy"],
492                    "grammar":"%YAML 1.2\n---\nname: Toy\nfile_extensions: [toy]\nscope: source.toy\ncontexts:\n  main:\n    - match: magic\n      scope: keyword.control.toy\n"})
493                }
494                "prepare" => {
495                    json!({"revision":format!("{:x}",Sha256::digest(r["sources"].to_string()))})
496                }
497                "augment" => {
498                    json!({"source":format!("{}\n\n## Extension content\n",r["source"].as_str().unwrap())})
499                }
500                "embed" => {
501                    json!({"html":"<svg role=\"img\"><text>Prepared toy diagram</text></svg>"})
502                }
503                "view" => {
504                    json!({"layout":"workspace","title":"Toy","content":format!("<h1>Toy viewer</h1><p>{}</p>",r["revision"].as_str().unwrap())})
505                }
506                "targets" => json!({"ids":["main"]}),
507                "route" => json!({"body":r["revision"],"mime":"text/plain","status":200}),
508                _ => bail!("Unknown toy operation"),
509            })
510        }
511    }
512
513    #[test]
514    fn another_language_uses_the_same_capture_render_targets_and_watch_contract() {
515        install_loader(Arc::new(Toy));
516        let dir =
517            std::env::temp_dir().join(format!("devpage-extension-contract-{}", std::process::id()));
518        let _ = std::fs::remove_dir_all(&dir);
519        std::fs::create_dir_all(dir.join("model/nested")).unwrap();
520        std::fs::write(dir.join("model/nested/a.toy"), "first").unwrap();
521        std::fs::write(dir.join("model/ignored.rs"), "not an input").unwrap();
522        std::fs::write(
523            dir.join("page.md"),
524            "# Page\n\n```toy\nmagic\n```\n\n![Toy](model/nested/a.toy#main)",
525        )
526        .unwrap();
527        std::fs::write(dir.join("devpage.yml"),"kind: site\ntitle: Toy\nroot: page.md\nwatch: [page.md]\nextensions:\n  toy:\n    package: ./toy-package\n    config:\n      input: model\n").unwrap();
528        let dir = dir.canonicalize().unwrap();
529        let scope = ServedFolder::new(&dir).unwrap();
530        let doc = crate::document::Document::load(&dir.join("devpage.yml"), &scope).unwrap();
531        let bindings = for_document(&doc.path());
532        assert_eq!(bindings.len(), 1);
533        assert!(!bindings[0].prepare().unwrap());
534        let first = bindings[0].view(&dir.join("model/nested/a.toy")).unwrap();
535        let rendered = crate::page::content(
536            &crate::widgets::Widgets::of(&doc, &crate::widgets::Modules::default()),
537            &dir.join("page.md"),
538            std::fs::read_to_string(dir.join("page.md")).unwrap(),
539        );
540        assert!(rendered.html().contains("hl-keyword"));
541        assert!(rendered.html().contains("Prepared toy diagram"));
542        assert!(rendered.ids().contains("extension-content"));
543        assert!(
544            rendered
545                .embeds()
546                .iter()
547                .any(|t| t == "model/nested/a.toy#main")
548        );
549        assert_eq!(
550            bindings[0].ids(&dir.join("model/nested/a.toy")).unwrap(),
551            vec!["main"]
552        );
553        let folder = crate::folder::Folder::new(Arc::new(doc));
554        assert!(folder.matters(&dir.join("model/nested/new.toy"), false));
555        std::fs::write(dir.join("model/nested/a.toy"), "second").unwrap();
556        assert!(changed(&scope, &[dir.join("model/nested/a.toy")]));
557        assert_ne!(
558            first,
559            bindings[0].view(&dir.join("model/nested/a.toy")).unwrap()
560        );
561        // Failure is visible; stale model data is not presented as current.
562        std::fs::remove_dir_all(dir.join("model")).unwrap();
563        assert!(bindings[0].prepare().is_err());
564        assert!(bindings[0].view(&dir.join("model/nested/a.toy")).is_err());
565        std::fs::create_dir_all(dir.join("model")).unwrap();
566        assert!(bindings[0].prepare().unwrap());
567        assert!(bindings[0].view(&dir.join("model/a.toy")).is_ok());
568        instances().lock().unwrap().remove(&dir.join("devpage.yml"));
569        std::fs::remove_dir_all(dir).unwrap();
570    }
571}