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;
6pub use browser::imported_module;
7use serde::{Deserialize, Serialize};
8use serde_json::{Value, json};
9use sha2::{Digest, Sha256};
10use std::{
11    collections::BTreeMap,
12    path::{Path, PathBuf},
13    sync::{Arc, Mutex, OnceLock},
14};
15/// An extension's package, loaded: what devpage asks, in JSON, to read its
16/// input and show its files.
17pub trait Package: Send + Sync {
18    /// The package's reply to `request`, a JSON object whose `op` names what is
19    /// asked: `create`, `prepare`, `view`, `augment`, `embed`, `targets` or
20    /// `route`.
21    fn invoke(&self, request: Value) -> Result<Value>;
22    /// The program the package keeps running beside devpage — none, unless the
23    /// package says otherwise.
24    fn process(&self) -> Option<Process> {
25        None
26    }
27}
28/// A package's process: the long-running program devpage starts for it, and
29/// passes the requests under the extension's `live/` address to.
30#[derive(Clone, Debug, PartialEq)]
31pub struct Process {
32    /// The program and its arguments, as the package's `run` lists them.
33    pub command: Vec<String>,
34    /// The package's folder, which the program is started in.
35    pub folder: PathBuf,
36}
37/// An address an extension's process answers — under its `live/`, or a page
38/// under its `pages/` — and what answers it.
39#[derive(Clone, Debug)]
40pub struct Live {
41    /// What names the bound extension among all of them: `<owner>/<id>`.
42    pub key: String,
43    /// The extension's name under the document's `extensions:`.
44    pub id: String,
45    /// The package's process — `None` when it has none.
46    pub process: Option<Process>,
47    /// What the extension is configured with, as JSON.
48    pub config: String,
49    /// The folder of the document file that configures the extension — the
50    /// served folder, for the live session devpage binds itself.
51    pub folder: PathBuf,
52    /// What the process is asked for, without a leading `/`: the address
53    /// past `live/`, or a page's from `pages/` on.
54    pub rest: String,
55}
56/// What loads an extension's package from its bundle; the executable installs
57/// the native one.
58pub trait Loader: Send + Sync {
59    /// The package bundled at `path`.
60    fn load(&self, path: &Path) -> Result<Arc<dyn Package>>;
61}
62/// The loader the executable installed; until it does, no extension can be
63/// configured.
64static LOADER: OnceLock<Arc<dyn Loader>> = OnceLock::new();
65/// Installs `loader` as the one every package is loaded with; a second call is
66/// ignored.
67pub fn install_loader(loader: Arc<dyn Loader>) {
68    let _ = LOADER.set(loader);
69}
70/// Every configured document's extensions, by the document's file.
71static INSTANCES: OnceLock<Mutex<BTreeMap<PathBuf, Vec<Binding>>>> = OnceLock::new();
72/// Every configured document's extensions, by the document's file — empty at
73/// first.
74fn instances() -> &'static Mutex<BTreeMap<PathBuf, Vec<Binding>>> {
75    INSTANCES.get_or_init(Default::default)
76}
77/// The system extension that is the live session: its name under a
78/// document's `extensions:`, and in its address.
79pub const LIVE: &str = "live";
80/// The package defaults for a local serving process and its shared session.
81#[derive(Clone, Default)]
82struct Local {
83    /// The session package when this local server enables it.
84    session: Option<Arc<dyn Package>>,
85    /// Extension defaults resolved relative to the global configuration.
86    packages: BTreeMap<String, Config>,
87    /// The entry document that configures this project’s shared session.
88    entry: Option<PathBuf>,
89}
90
91/// Local configuration by served folder and mount.
92static LOCAL: OnceLock<Mutex<BTreeMap<ServedFolder, Local>>> = OnceLock::new();
93
94/// Local serving configuration, initially empty for offline commands.
95fn local() -> &'static Mutex<BTreeMap<ServedFolder, Local>> {
96    LOCAL.get_or_init(Default::default)
97}
98
99/// Enables globally configured packages during loopback serving. Paths are
100/// relative to the global configuration file's folder.
101pub fn serve_packages(scope: &ServedFolder, home: &Path, mut packages: BTreeMap<String, Config>) {
102    for config in packages.values_mut() {
103        if let Some(path) = &mut config.package {
104            *path = home.join(&*path).to_string_lossy().into_owned();
105        }
106    }
107    local()
108        .lock()
109        .unwrap()
110        .entry(scope.clone())
111        .or_default()
112        .packages = packages;
113}
114
115/// Enables the shared live-session package for this served project.
116pub fn serve_live(scope: &ServedFolder, package: Arc<dyn Package>) {
117    local()
118        .lock()
119        .unwrap()
120        .entry(scope.clone())
121        .or_default()
122        .session = Some(package);
123}
124
125/// The shared session reads its project configuration from the entry document.
126pub fn serve_entry(scope: &ServedFolder, document: PathBuf) {
127    local()
128        .lock()
129        .unwrap()
130        .entry(scope.clone())
131        .or_default()
132        .entry = Some(document);
133}
134
135/// Applies a document's entries over the global defaults, before system
136/// extensions and package bindings consume their configuration.
137pub(crate) fn configured(
138    scope: &ServedFolder,
139    document: BTreeMap<String, Config>,
140) -> BTreeMap<String, Config> {
141    let mut configs = local()
142        .lock()
143        .unwrap()
144        .get(scope)
145        .map(|local| local.packages.clone())
146        .unwrap_or_default();
147    configs.extend(document);
148    configs
149}
150/// Whether `config`, what a document configures the live session with, leaves
151/// it on: it does unless it says `enabled: false`.
152fn enabled(config: &serde_yaml::Value) -> Result<bool> {
153    match config {
154        serde_yaml::Value::Null => Ok(true),
155        serde_yaml::Value::Mapping(map) => match map.get("enabled") {
156            None => Ok(true),
157            Some(serde_yaml::Value::Bool(enabled)) => Ok(*enabled),
158            Some(_) => bail!("extensions: {LIVE}: config: enabled is not true or false"),
159        },
160        _ => bail!("extensions: {LIVE}: config is not a mapping"),
161    }
162}
163/// An extension as a document's `extensions:` names it: its package and what it
164/// is configured with.
165#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
166#[serde(deny_unknown_fields)]
167pub struct Config {
168    /// A document can turn off a package enabled globally.
169    pub enabled: Option<bool>,
170    /// The package's bundle; left out only for a system extension such as
171    /// [`code`](crate::code) or the live session, [`LIVE`].
172    pub package: Option<String>,
173    /// What the package is created with, as written under `config:`; null when
174    /// left out.
175    #[serde(default)]
176    pub config: serde_yaml::Value,
177}
178/// An extension bound to a document: its package, the input it reads and what
179/// it last prepared from it. Clones share one state; a
180/// [`snapshot`](Self::snapshot) does not.
181#[derive(Clone)]
182pub struct Binding(Arc<Mutex<State>>);
183impl std::fmt::Debug for Binding {
184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185        f.write_str("ExtensionBinding")
186    }
187}
188/// What a binding holds: its package, how it was configured and what it last
189/// prepared.
190#[derive(Clone)]
191struct State {
192    /// The extension's name under the document's `extensions:`.
193    id: String,
194    /// The document's whole `extensions:`, as JSON, and whether the live
195    /// session is bound to it — what tells a changed configuration from the
196    /// bound one.
197    configuration: String,
198    /// The instance's id: the first 16 hex digits of the SHA-256 of the
199    /// document's path, `id` and `configuration` — or, for the live session
200    /// devpage binds itself, of the served folder's path and `id`: one for
201    /// every document in it.
202    owner: String,
203    /// Whether devpage bound it itself, as the live session: no document
204    /// names its package.
205    system: bool,
206    /// The package, loaded by the installed [`Loader`]; each request names
207    /// this binding by `owner`.
208    package: Arc<dyn Package>,
209    /// The served folder its input and the files it shows must lie in.
210    scope: ServedFolder,
211    /// What the extension is configured with, as JSON.
212    config: Value,
213    /// The folder of the document file that configures it — the served
214    /// folder, for the live session devpage binds itself.
215    folder: PathBuf,
216    /// The file or folder it reads, as the package's `create` reply names it —
217    /// `None` when it reads none.
218    input: Option<PathBuf>,
219    /// The package's reply to `create`: the suffixes it owns, its input and the
220    /// suffixes read there, its grammar, widgets and styles.
221    descriptor: Value,
222    /// Widget placements from this declaration.
223    places: crate::document::Places,
224    /// The modules, widgets and stylesheets the package ships for the browser,
225    /// compiled.
226    browser: Arc<Browser>,
227    /// What the package named its last preparation — empty before the first.
228    revision: String,
229    /// Why the last preparation failed — `None` when it didn't, or when the
230    /// reply only lacked a revision. While set, every call fails.
231    error: Option<String>,
232    /// The input last prepared from: each file's contents, by its name in the
233    /// served folder.
234    sources: BTreeMap<String, String>,
235}
236impl Binding {
237    /// The address the binding of `s` answers under:
238    /// `<mount>/__devpage/extensions/<owner>/<id>/`.
239    fn base(s: &State) -> String {
240        format!(
241            "{}/__devpage/extensions/{}/{}/",
242            s.scope.mount(),
243            s.owner,
244            s.id
245        )
246    }
247    /// The extension's name under the document's `extensions:`, and the
248    /// address it answers under.
249    pub fn address(&self) -> (String, String) {
250        let s = self.0.lock().unwrap();
251        (s.id.clone(), Self::base(&s))
252    }
253    /// Whether this is the live session devpage binds itself, not a package
254    /// the document names.
255    pub fn is_session(&self) -> bool {
256        self.0.lock().unwrap().system
257    }
258    /// The widget placements declared by this package.
259    pub fn places(&self) -> crate::document::Places {
260        self.0.lock().unwrap().places.clone()
261    }
262    /// The address of each of the package's widgets' modules, by widget name.
263    pub fn widget_urls(&self) -> BTreeMap<String, String> {
264        let s = self.0.lock().unwrap();
265        s.browser.widgets(&Self::base(&s))
266    }
267    /// The addresses of the package's stylesheets.
268    pub fn style_urls(&self) -> Vec<String> {
269        let s = self.0.lock().unwrap();
270        s.browser.styles(&Self::base(&s))
271    }
272    /// The package's view of `file`, a file it owns: its `layout`, `title` and
273    /// `content`.
274    pub fn view(&self, file: &Path) -> Result<Value> {
275        let s = self.0.lock().unwrap();
276        let path = s
277            .scope
278            .name(file)
279            .ok_or_else(|| anyhow!("View outside served folder"))?;
280        drop(s);
281        self.call("view", json!({"path":path}))
282    }
283
284    /// Pin this render to its prepared revision while the watcher prepares the next.
285    pub fn snapshot(&self) -> Self {
286        Self(Arc::new(Mutex::new(self.0.lock().unwrap().clone())))
287    }
288    /// The package's reply to `op`, asked with `extra` and the instance, its
289    /// base address and revision. An error while the last preparation failed.
290    fn call(&self, op: &str, extra: Value) -> Result<Value> {
291        let s = self.0.lock().unwrap();
292        if let Some(error) = &s.error {
293            bail!("Extension preparation failed: {error}");
294        }
295        let mut request = extra;
296        request["op"] = op.into();
297        request["instance"] = s.owner.clone().into();
298        request["base"] = format!(
299            "{}/__devpage/extensions/{}/{}/",
300            s.scope.mount(),
301            s.owner,
302            s.id
303        )
304        .into();
305        request["revision"] = s.revision.clone().into();
306        s.package.invoke(request)
307    }
308    /// The file or folder the extension reads — `None` when it reads none.
309    pub fn input(&self) -> Option<PathBuf> {
310        self.0.lock().unwrap().input.clone()
311    }
312    /// Whether `file` is one the extension shows: its suffix is one the package
313    /// declared and, when `file` is absolute, it lies in the input.
314    pub fn owns(&self, file: &Path) -> bool {
315        let s = self.0.lock().unwrap();
316        if file.is_absolute()
317            && !s
318                .input
319                .as_ref()
320                .is_some_and(|input| file.starts_with(input))
321        {
322            return false;
323        }
324        let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");
325        s.descriptor["file_extensions"]
326            .as_array()
327            .is_some_and(|a| a.iter().any(|v| v.as_str() == Some(ext)))
328    }
329    /// Whether a new revision was prepared: the input is read again, and the
330    /// package prepares from it unless it is unchanged, the last preparation
331    /// succeeded and a revision is held. A failure to read or prepare is kept,
332    /// and fails every call until a preparation succeeds; a reply without a
333    /// revision fails only this preparation.
334    pub fn prepare(&self) -> Result<bool> {
335        let mut s = self.0.lock().unwrap();
336        let mut sources = BTreeMap::new();
337        fn read(
338            scope: &ServedFolder,
339            p: &Path,
340            files: &mut BTreeMap<String, String>,
341            extensions: &[Value],
342        ) -> Result<()> {
343            if std::fs::symlink_metadata(p)?.file_type().is_symlink() {
344                bail!("Symlinked extension input {}", p.display());
345            }
346            let canonical = p.canonicalize()?;
347            if !canonical.starts_with(scope.path()) {
348                bail!("Extension input outside served folder");
349            }
350            if p.is_dir() {
351                for entry in std::fs::read_dir(p)? {
352                    let entry = entry?;
353                    if !entry.file_name().to_string_lossy().starts_with('.') {
354                        read(scope, &entry.path(), files, extensions)?;
355                    }
356                }
357            } else if p
358                .extension()
359                .and_then(|e| e.to_str())
360                .is_some_and(|ext| extensions.iter().any(|v| v.as_str() == Some(ext)))
361            {
362                files.insert(
363                    scope
364                        .name(p)
365                        .ok_or_else(|| anyhow!("Input outside served folder"))?,
366                    std::fs::read_to_string(p)?,
367                );
368            }
369            Ok(())
370        }
371        if let Some(input) = &s.input {
372            let extensions = s.descriptor["input_extensions"]
373                .as_array()
374                .ok_or_else(|| anyhow!("Extension must declare input_extensions"))?;
375            if let Err(error) = read(&s.scope, input, &mut sources, extensions) {
376                s.error = Some(error.to_string());
377                return Err(error);
378            }
379        }
380        if s.error.is_none() && s.sources == sources && !s.revision.is_empty() {
381            return Ok(false);
382        }
383        let reply = match s
384            .package
385            .invoke(json!({"op":"prepare","instance":s.owner,"sources":sources}))
386        {
387            Ok(reply) => reply,
388            Err(error) => {
389                s.error = Some(format!("{error:#}"));
390                return Err(error);
391            }
392        };
393        s.revision = reply["revision"]
394            .as_str()
395            .ok_or_else(|| anyhow!("Extension preparation omitted revision"))?
396            .into();
397        s.sources = sources;
398        s.error = None;
399        Ok(true)
400    }
401    /// The syntax definition the package highlights its language with — `None`
402    /// when it brings none.
403    pub fn grammar(&self) -> Option<String> {
404        self.0.lock().unwrap().descriptor["grammar"]
405            .as_str()
406            .map(String::from)
407    }
408    /// `source`, the page at `file`, as the package augments it — unchanged
409    /// when the reply has no `source`.
410    pub fn transform(&self, file: &Path, source: &str) -> Result<String> {
411        let s = self.0.lock().unwrap();
412        let path = s
413            .scope
414            .name(file)
415            .ok_or_else(|| anyhow!("Page outside served folder"))?;
416        drop(s);
417        let reply = self.call("augment", json!({"path":path,"source":source}))?;
418        Ok(reply["source"].as_str().unwrap_or(source).into())
419    }
420    /// The HTML the package shows `target` as in the page at `file`, with
421    /// `label`; `identity` is its place among the page's `src` targets.
422    pub fn embed(&self, file: &Path, target: &str, label: &str, identity: usize) -> Result<String> {
423        let s = self.0.lock().unwrap();
424        let path = s
425            .scope
426            .name(file)
427            .ok_or_else(|| anyhow!("Page outside served folder"))?;
428        drop(s);
429        Ok(self.call(
430            "embed",
431            json!({"page":path,"target":target,"label":label,"identity":identity}),
432        )?["html"]
433            .as_str()
434            .ok_or_else(|| anyhow!("Missing embed HTML"))?
435            .into())
436    }
437    /// The ids a link may point at inside `file`, a file the extension owns.
438    pub fn ids(&self, file: &Path) -> Result<Vec<String>> {
439        let s = self.0.lock().unwrap();
440        let path = s
441            .scope
442            .name(file)
443            .ok_or_else(|| anyhow!("Target outside served folder"))?;
444        drop(s);
445        Ok(self.call("targets", json!({"path":path}))?["ids"]
446            .as_array()
447            .into_iter()
448            .flatten()
449            .filter_map(|v| v.as_str().map(String::from))
450            .collect())
451    }
452}
453/// Binds the extensions `configs` to the document at `doc`, each package loaded
454/// from its bundle under `base`, and prepares each; with them the live
455/// session, where it is [on](serve_live) in `scope`, unless the document's
456/// `live` says `enabled: false` in its `config` or names a package of its
457/// own. Nothing to bind unbinds the document. A configuration already bound
458/// in `scope` is kept as it is.
459pub fn configure(
460    doc: &Path,
461    base: &Path,
462    scope: &ServedFolder,
463    mut configs: BTreeMap<String, Config>,
464) -> Result<()> {
465    // `live` with no package is the system extension: the live session.
466    let live_enabled = configs
467        .get(LIVE)
468        .is_none_or(|config| config.enabled != Some(false));
469    configs.retain(|_, config| config.enabled != Some(false));
470    let own = match configs.get(LIVE) {
471        Some(config) if config.package.is_none() => configs.remove(LIVE).map(|c| c.config),
472        _ => None,
473    };
474    let on = own.as_ref().map(enabled).transpose()?.unwrap_or(true);
475    let session = (on && live_enabled && !configs.contains_key(LIVE))
476        .then(|| {
477            local()
478                .lock()
479                .unwrap()
480                .get(scope)
481                .and_then(|local| local.session.clone())
482        })
483        .flatten();
484    let mut guard = instances().lock().unwrap();
485    if configs.is_empty() && session.is_none() {
486        guard.remove(doc);
487        return Ok(());
488    }
489    let configuration = serde_json::to_string(&(&configs, &own, session.is_some()))?;
490    if guard.get(doc).is_some_and(|bindings| {
491        bindings.iter().all(|b| {
492            let s = b.0.lock().unwrap();
493            s.configuration == configuration && s.scope == *scope
494        })
495    }) {
496        return Ok(());
497    }
498    let mut bindings = vec![];
499    let mut parts = BTreeMap::new();
500    let mut claims: std::collections::BTreeSet<String> = ["md", "yml", "yaml", "design"]
501        .into_iter()
502        .map(String::from)
503        .collect();
504    for (id, config) in configs {
505        let Some(path) = &config.package else {
506            bail!("extensions: {id}: package is required — {id} is not a system extension");
507        };
508        let loader = LOADER
509            .get()
510            .ok_or_else(|| anyhow!("Native extension loader unavailable"))?;
511        let package = loader
512            .load(&base.join(path))
513            .map_err(|e| anyhow!("Extension {id}: {e:#}"))?;
514        let owner = format!(
515            "{:x}",
516            Sha256::digest(format!("{}:{id}:{configuration}", doc.display()))
517        )[..16]
518            .to_string();
519        let binding = bind(
520            Bound {
521                id: id.clone(),
522                owner,
523                system: false,
524                package,
525                config: serde_json::to_value(&config.config)?,
526                folder: base,
527            },
528            &configuration,
529            scope,
530            &mut claims,
531        )?;
532        if let Some(path) = binding.0.lock().unwrap().descriptor["world"].as_str() {
533            parts.insert(id, path.to_owned());
534        }
535        bindings.push(binding);
536    }
537    if let Some(package) = session {
538        let mut config = serde_json::to_value(own.unwrap_or_default())?;
539        if !parts.is_empty() {
540            if config["world"].is_null() {
541                config["world"] = json!({});
542            }
543            let world = config["world"]
544                .as_object_mut()
545                .ok_or_else(|| anyhow!("live: world must be a mapping"))?;
546            for (part, path) in parts {
547                world.insert(part, path.into());
548            }
549        }
550        let owner = format!(
551            "{:x}",
552            Sha256::digest(format!("{}:{LIVE}", scope.path().display()))
553        )[..16]
554            .to_string();
555        bindings.push(bind(
556            Bound {
557                id: LIVE.to_string(),
558                owner,
559                system: true,
560                package,
561                config,
562                folder: scope.path(),
563            },
564            &configuration,
565            scope,
566            &mut claims,
567        )?);
568    }
569    guard.insert(doc.to_path_buf(), bindings);
570    Ok(())
571}
572/// An extension about to be bound to a document: what [`bind`] makes a
573/// [`Binding`] from.
574struct Bound<'a> {
575    /// The extension's name under the document's `extensions:`.
576    id: String,
577    /// The instance's id.
578    owner: String,
579    /// Whether devpage binds it itself, as the live session.
580    system: bool,
581    /// The package, loaded.
582    package: Arc<dyn Package>,
583    /// What the extension is configured with, as JSON.
584    config: Value,
585    /// The folder its input is named from and its program is told as the
586    /// root: the document file's, or the served folder for the live session.
587    folder: &'a Path,
588}
589/// Creates and prepares the extension `bound` in `scope`, under the document
590/// configuration `configuration`; `claims` holds the file suffixes taken so
591/// far, and gains the package's.
592fn bind(
593    bound: Bound,
594    configuration: &str,
595    scope: &ServedFolder,
596    claims: &mut std::collections::BTreeSet<String>,
597) -> Result<Binding> {
598    let Bound {
599        id,
600        owner,
601        system,
602        package,
603        config,
604        folder,
605    } = bound;
606    let descriptor =
607        package.invoke(json!({"op":"create","instance":owner,"id":id,"config":config}))?;
608    // A package that shows no files and reads no input may leave both out.
609    let none = Vec::new();
610    let listed = |field: &str| -> Result<&Vec<Value>> {
611        match &descriptor[field] {
612            Value::Null => Ok(&none),
613            Value::Array(listed) => Ok(listed),
614            _ => bail!("Extension {id} {field} is not a list"),
615        }
616    };
617    let reads = !listed("input_extensions")?.is_empty();
618    for suffix in listed("file_extensions")? {
619        let suffix = suffix
620            .as_str()
621            .filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric()))
622            .ok_or_else(|| anyhow!("Extension {id} invalid file suffix"))?;
623        if !claims.insert(suffix.into()) {
624            bail!("Extension {id} file format {suffix} is already claimed");
625        }
626    }
627    if let Some(grammar) = descriptor["grammar"].as_str() {
628        let syntax = syntect::parsing::SyntaxDefinition::load_from_str(grammar, true, None)
629            .map_err(|e| anyhow!("Extension {id} grammar: {e}"))?;
630        if syntax
631            .file_extensions
632            .iter()
633            .any(|s| crate::highlight::builtin_language(s))
634        {
635            bail!("Extension {id} cannot replace a built-in language");
636        }
637    }
638    let input = match descriptor["input"].as_str() {
639        Some(input) => {
640            let input = folder.join(input);
641            if !input.canonicalize()?.starts_with(scope.path()) {
642                bail!("Extension {id} input outside served folder");
643            }
644            Some(input)
645        }
646        None if reads || !listed("file_extensions")?.is_empty() => {
647            bail!("Extension input missing")
648        }
649        None => None,
650    };
651    let browser = Browser::new(
652        &descriptor,
653        &format!("{}/__devpage/extensions/{owner}/{id}/", scope.mount()),
654    )?;
655    let places = serde_json::from_value(descriptor.get("places").cloned().unwrap_or(json!({})))?;
656    let binding = Binding(Arc::new(Mutex::new(State {
657        id,
658        configuration: configuration.to_string(),
659        owner,
660        system,
661        package,
662        scope: scope.clone(),
663        config,
664        folder: folder.to_path_buf(),
665        input,
666        descriptor,
667        places,
668        browser: Arc::new(browser),
669        revision: String::new(),
670        error: None,
671        sources: BTreeMap::new(),
672    })));
673    binding.prepare()?;
674    Ok(binding)
675}
676/// The extensions bound to the document at `doc` — none when it has none.
677pub fn for_document(doc: &Path) -> Vec<Binding> {
678    instances()
679        .lock()
680        .unwrap()
681        .get(doc)
682        .cloned()
683        .unwrap_or_default()
684}
685/// The input of every extension bound in `scope`, for the watcher to watch.
686pub fn input_roots(scope: &ServedFolder) -> Vec<PathBuf> {
687    instances()
688        .lock()
689        .unwrap()
690        .values()
691        .flatten()
692        .filter(|b| b.0.lock().unwrap().scope == *scope)
693        .filter_map(Binding::input)
694        .collect()
695}
696/// Whether an extension in `scope` prepared anew after `files` changed: each
697/// whose input holds one of them, or lies in one, prepares again. A failed
698/// preparation counts as a change.
699pub fn changed(scope: &ServedFolder, files: &[PathBuf]) -> bool {
700    let all: Vec<_> = instances()
701        .lock()
702        .unwrap()
703        .values()
704        .flatten()
705        .filter(|b| b.0.lock().unwrap().scope == *scope)
706        .cloned()
707        .collect();
708    let mut changed = false;
709    for b in all {
710        let Some(input) = b.input() else {
711            continue;
712        };
713        if files
714            .iter()
715            .any(|p| p.starts_with(&input) || input.starts_with(p))
716        {
717            changed |= b.prepare().unwrap_or(true);
718        }
719    }
720    changed
721}
722/// The extensions of the document that owns `file` in `folder` — the entry
723/// document's when none does.
724pub fn for_file(file: &Path, folder: &crate::folder::Folder) -> Vec<Binding> {
725    let path = folder
726        .owner(file)
727        .and_then(|o| o.document.ok())
728        .map(|d| d.path())
729        .unwrap_or_else(|| folder.entry().path());
730    for_document(&path)
731}
732/// What answers `path` when it is under an extension's `live/` address in
733/// `scope`: the bound extension and its process. `None` when it is no such
734/// address.
735pub fn live(path: &str, scope: &ServedFolder) -> Option<Live> {
736    let (mut live, _) = bound_at(path, scope, None)?;
737    live.rest = live.rest.strip_prefix("live/")?.to_string();
738    Some(live)
739}
740/// The page of an extension `path` names in `scope`, `pages/<page>` under the
741/// extension's address: what answers it, asked for `pages/<page>`; the page,
742/// as its extension names it; and the file of the document it is drawn in —
743/// `entry` when that document binds the extension, else the first that does.
744/// `None` when `path` is no extension's page.
745pub fn page(path: &str, scope: &ServedFolder, entry: &Path) -> Option<(Live, String, PathBuf)> {
746    let (live, document) = bound_at(path, scope, Some(entry))?;
747    let page = live.rest.strip_prefix("pages/")?.to_string();
748    (!page.is_empty()).then_some((live, page, document))
749}
750/// The extension bound in `scope` whose address `path` is under, with
751/// everything past that address as its [`Live::rest`], and the file of a
752/// document that binds it: `preferred` when it does, else the first.
753fn bound_at(path: &str, scope: &ServedFolder, preferred: Option<&Path>) -> Option<(Live, PathBuf)> {
754    let suffix = path
755        .trim_start_matches('/')
756        .strip_prefix("__devpage/extensions/")?;
757    let (owner, tail) = suffix.split_once('/')?;
758    let (id, rest) = tail.split_once('/')?;
759    let guard = instances().lock().unwrap();
760    let found = |(document, bindings): (&PathBuf, &Vec<Binding>)| {
761        bindings.iter().find_map(|b| {
762            let s = b.0.lock().unwrap();
763            (s.owner == owner && s.id == id && s.scope == *scope).then(|| {
764                let live = Live {
765                    key: format!("{owner}/{id}"),
766                    id: s.id.clone(),
767                    process: s.package.process(),
768                    config: s.config.to_string(),
769                    folder: s.folder.clone(),
770                    rest: rest.to_string(),
771                };
772                (live, document.clone())
773            })
774        })
775    };
776    let entry = (id == LIVE)
777        .then(|| {
778            local()
779                .lock()
780                .unwrap()
781                .get(scope)
782                .and_then(|local| local.entry.clone())
783        })
784        .flatten();
785    preferred
786        .or(entry.as_deref())
787        .and_then(|preferred| guard.get_key_value(preferred))
788        .and_then(found)
789        .or_else(|| guard.iter().find_map(found))
790}
791/// Whether `key`, a [`Live::key`], still names a bound extension: one whose
792/// document was not loaded again with another configuration.
793pub fn bound(key: &str) -> bool {
794    let guard = instances().lock().unwrap();
795    guard.values().flatten().any(|b| {
796        let s = b.0.lock().unwrap();
797        key.split_once('/') == Some((&s.owner, &s.id))
798    })
799}
800/// The reply to `path` when it is an extension's address in `scope`: a browser
801/// file the package ships, or else what the package routes it to. `None` when
802/// it is no extension's.
803pub fn route(path: &str, scope: &ServedFolder) -> Option<Result<Value>> {
804    let suffix = path
805        .trim_start_matches('/')
806        .strip_prefix("__devpage/extensions/")?;
807    let (owner, tail) = suffix.split_once('/')?;
808    let (id, tail) = tail.split_once('/')?;
809    let all: Vec<_> = instances()
810        .lock()
811        .unwrap()
812        .values()
813        .flatten()
814        .cloned()
815        .collect();
816    all.into_iter()
817        .find(|b| {
818            let s = b.0.lock().unwrap();
819            s.owner == owner && s.id == id && s.scope == *scope
820        })
821        .map(|b| {
822            let response = {
823                let s = b.0.lock().unwrap();
824                s.browser.response(tail)
825            };
826            response.map_or_else(|| b.call("route", json!({"path":tail})), Ok)
827        })
828}
829
830#[cfg(test)]
831mod tests {
832    use super::*;
833    use codespec_rust_macro::spec;
834    struct Toy;
835    impl Loader for Toy {
836        fn load(&self, _: &Path) -> Result<Arc<dyn Package>> {
837            Ok(Arc::new(Toy))
838        }
839    }
840    impl Package for Toy {
841        fn invoke(&self, r: Value) -> Result<Value> {
842            Ok(match r["op"].as_str().unwrap() {
843                "create" => {
844                    json!({"input":r["config"]["input"],"input_extensions":["toy","md"],"file_extensions":["toy"],
845                    "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"})
846                }
847                "prepare" => {
848                    json!({"revision":format!("{:x}",Sha256::digest(r["sources"].to_string()))})
849                }
850                "augment" => {
851                    json!({"source":format!("{}\n\n## Extension content\n",r["source"].as_str().unwrap())})
852                }
853                "embed" => {
854                    json!({"html":"<svg role=\"img\"><text>Prepared toy diagram</text></svg>"})
855                }
856                "view" => {
857                    json!({"layout":"workspace","title":"Toy","content":format!("<h1>Toy viewer</h1><p>{}</p>",r["revision"].as_str().unwrap())})
858                }
859                "targets" => json!({"ids":["main"]}),
860                "route" => json!({"body":r["revision"],"mime":"text/plain","status":200}),
861                _ => bail!("Unknown toy operation"),
862            })
863        }
864    }
865
866    #[test]
867    #[spec("hot-reload-works-for-every-page")]
868    #[spec("a-broken-file-shows-its-error")]
869    fn another_language_uses_the_same_capture_render_targets_and_watch_contract() {
870        install_loader(Arc::new(Toy));
871        let dir =
872            std::env::temp_dir().join(format!("devpage-extension-contract-{}", std::process::id()));
873        let _ = std::fs::remove_dir_all(&dir);
874        std::fs::create_dir_all(dir.join("model/nested")).unwrap();
875        std::fs::write(dir.join("model/nested/a.toy"), "first").unwrap();
876        std::fs::write(dir.join("model/ignored.rs"), "not an input").unwrap();
877        std::fs::write(
878            dir.join("page.md"),
879            "# Page\n\n```toy\nmagic\n```\n\n![Toy](model/nested/a.toy#main)",
880        )
881        .unwrap();
882        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();
883        let dir = dir.canonicalize().unwrap();
884        let scope = ServedFolder::new(&dir).unwrap();
885        let doc = crate::document::Document::load(&dir.join("devpage.yml"), &scope).unwrap();
886        let bindings = for_document(&doc.path());
887        assert_eq!(bindings.len(), 1);
888        assert!(!bindings[0].prepare().unwrap());
889        let first = bindings[0].view(&dir.join("model/nested/a.toy")).unwrap();
890        let rendered = crate::page::content(
891            &crate::widgets::Widgets::of(&doc, &crate::widgets::Modules::default()),
892            &dir.join("page.md"),
893            std::fs::read_to_string(dir.join("page.md")).unwrap(),
894        );
895        assert!(rendered.html().contains("hl-keyword"));
896        assert!(rendered.html().contains("Prepared toy diagram"));
897        assert!(rendered.ids().contains("extension-content"));
898        assert!(
899            rendered
900                .embeds()
901                .iter()
902                .any(|t| t == "model/nested/a.toy#main")
903        );
904        assert_eq!(
905            bindings[0].ids(&dir.join("model/nested/a.toy")).unwrap(),
906            vec!["main"]
907        );
908        let folder = crate::folder::Folder::new(Arc::new(doc));
909        assert!(folder.matters(&dir.join("model/nested/new.toy"), false));
910        std::fs::write(dir.join("model/nested/a.toy"), "second").unwrap();
911        assert!(changed(&scope, &[dir.join("model/nested/a.toy")]));
912        assert_ne!(
913            first,
914            bindings[0].view(&dir.join("model/nested/a.toy")).unwrap()
915        );
916        // Failure is visible; stale model data is not presented as current.
917        std::fs::remove_dir_all(dir.join("model")).unwrap();
918        assert!(bindings[0].prepare().is_err());
919        assert!(bindings[0].view(&dir.join("model/nested/a.toy")).is_err());
920        std::fs::create_dir_all(dir.join("model")).unwrap();
921        assert!(bindings[0].prepare().unwrap());
922        assert!(bindings[0].view(&dir.join("model/a.toy")).is_ok());
923        instances().lock().unwrap().remove(&dir.join("devpage.yml"));
924        std::fs::remove_dir_all(dir).unwrap();
925    }
926
927    /// A package that only runs a program, as the live session's does.
928    struct Session;
929    impl Package for Session {
930        fn invoke(&self, r: Value) -> Result<Value> {
931            Ok(match r["op"].as_str().unwrap() {
932                "create" => {
933                    json!({"places":{"navbar":["DevpageLiveTasksButton"],"panel":["DevpageLiveTasks"],"float":["DevpageLiveCanvas","DevpageLiveOrb"]}})
934                }
935                "prepare" => json!({"revision": "none"}),
936                _ => json!({}),
937            })
938        }
939        fn process(&self) -> Option<Process> {
940            Some(Process {
941                command: vec!["session".into()],
942                folder: PathBuf::from("/program"),
943            })
944        }
945    }
946
947    #[test]
948    fn the_live_session_is_one_for_a_served_folder_and_a_document_turns_it_off_or_replaces_it() {
949        use crate::document::Document;
950        install_loader(Arc::new(Toy));
951        let dir = std::env::temp_dir().join(format!("devpage-live-session-{}", std::process::id()));
952        let _ = std::fs::remove_dir_all(&dir);
953        for folder in ["widgets", "set", "off", "own/model"] {
954            std::fs::create_dir_all(dir.join(folder)).unwrap();
955        }
956        std::fs::write(dir.join("widgets/Mine.tsx"), "export default () => null;").unwrap();
957        std::fs::write(
958            dir.join("devpage.yml"),
959            "kind: site\ntitle: T\nroot: README.md\nwidgets: widgets\nplaces:\n  float: [Mine]\n",
960        )
961        .unwrap();
962        std::fs::write(dir.join("README.md"), "# T\n").unwrap();
963        std::fs::write(dir.join("lone.md"), "# Lone\n").unwrap();
964        std::fs::write(
965            dir.join("set/devpage.yml"),
966            "kind: doc\ntitle: S\nchapters: [a.md]\nextensions:\n  live:\n    config:\n      voice: calm\n",
967        )
968        .unwrap();
969        std::fs::write(dir.join("set/a.md"), "# A\n").unwrap();
970        std::fs::write(
971            dir.join("off/devpage.yml"),
972            "kind: doc\ntitle: O\nchapters: [a.md]\nextensions:\n  live:\n    config:\n      enabled: false\n",
973        )
974        .unwrap();
975        std::fs::write(dir.join("off/a.md"), "# A\n").unwrap();
976        std::fs::write(
977            dir.join("own/devpage.yml"),
978            "kind: doc\ntitle: W\nchapters: [a.md]\nextensions:\n  live:\n    package: ./package\n    config:\n      input: model\n",
979        )
980        .unwrap();
981        std::fs::write(dir.join("own/a.md"), "# A\n").unwrap();
982        let dir = dir.canonicalize().unwrap();
983        let scope = ServedFolder::new(&dir).unwrap();
984        let load = |path: &str| Document::load(&dir.join(path), &scope).unwrap();
985
986        // Off: no document has it, whatever it says of it.
987        for path in [
988            "devpage.yml",
989            "lone.md",
990            "set/devpage.yml",
991            "off/devpage.yml",
992        ] {
993            let document = load(path);
994            assert!(document.extensions.is_empty(), "{path}");
995            assert!(document.places.panel.is_empty(), "{path}");
996        }
997
998        serve_live(&scope, Arc::new(Session));
999        let site = load("devpage.yml");
1000        let (id, address) = site.extensions[0].address();
1001        assert_eq!(id, LIVE);
1002        assert!(site.extensions[0].is_session());
1003        // Its widgets come after the document's own.
1004        assert_eq!(site.places.navbar, ["DevpageLiveTasksButton"]);
1005        assert_eq!(site.places.panel, ["DevpageLiveTasks"]);
1006        assert_eq!(
1007            site.places.float,
1008            ["Mine", "DevpageLiveCanvas", "DevpageLiveOrb"]
1009        );
1010        // One address for every document: a lone Markdown file's, and one
1011        // that configures the session.
1012        for path in ["lone.md", "set/devpage.yml"] {
1013            let document = load(path);
1014            assert_eq!(document.extensions.len(), 1, "{path}");
1015            assert_eq!(document.extensions[0].address().1, address, "{path}");
1016            assert_eq!(document.places.panel, ["DevpageLiveTasks"], "{path}");
1017        }
1018        // Its program is told the served folder, and each document's own
1019        // configuration is kept with its binding.
1020        let asked = live(&format!("{address}live/socket"), &scope).unwrap();
1021        assert_eq!(asked.folder, dir);
1022        assert_eq!(asked.rest, "socket");
1023        assert!(asked.process.is_some());
1024        assert!(bound(&asked.key));
1025        let configured = for_document(&dir.join("set/devpage.yml"));
1026        assert_eq!(
1027            configured[0].0.lock().unwrap().config,
1028            json!({"voice": "calm"})
1029        );
1030
1031        // `enabled: false` turns it off for the document, and a package of
1032        // the document's own takes its place: devpage places nothing.
1033        let off = load("off/devpage.yml");
1034        assert!(off.extensions.is_empty());
1035        assert_eq!(off.places, Default::default());
1036        let own = load("own/devpage.yml");
1037        assert_eq!(own.extensions.len(), 1);
1038        assert!(!own.extensions[0].is_session());
1039        assert_ne!(own.extensions[0].address().1, address);
1040        assert_eq!(own.places, Default::default());
1041
1042        std::fs::write(
1043            dir.join("off/devpage.yml"),
1044            "kind: doc\ntitle: O\nchapters: [a.md]\nextensions:\n  live:\n    config:\n      enabled: sometimes\n",
1045        )
1046        .unwrap();
1047        let error = Document::load(&dir.join("off/devpage.yml"), &scope).unwrap_err();
1048        assert!(
1049            format!("{error:#}")
1050                .ends_with("extensions: live: config: enabled is not true or false"),
1051            "{error:#}"
1052        );
1053        std::fs::remove_dir_all(dir).unwrap();
1054    }
1055}