Skip to main content

devpage_core/extensions/
browser.rs

1//! Package-owned React modules, compiled through the same TSX compiler as widgets.
2use anyhow::{Result, anyhow, bail};
3use serde_json::{Value, json};
4use sha2::{Digest, Sha256};
5use std::{
6    collections::BTreeMap,
7    path::{Component, Path},
8};
9
10/// An extension package's browser side: its modules compiled to JavaScript, its
11/// widgets and its styles, served under an address that changes with their
12/// content.
13#[derive(Clone, Default)]
14pub(super) struct Browser {
15    /// The hash of the build and the package's sources, widgets and styles: the
16    /// address segment that changes whenever any of them does.
17    digest: String,
18    /// Each module's compiled JavaScript, by its path in the package.
19    modules: BTreeMap<String, String>,
20    /// Each widget's module path, by widget name.
21    widgets: BTreeMap<String, String>,
22    /// Each stylesheet's CSS, by its path in the package.
23    styles: BTreeMap<String, String>,
24}
25/// `path` with `.` and `..` resolved, as `/`-joined parts. An error when it
26/// climbs out of the package or isn't relative.
27fn normalized(path: &Path) -> Result<String> {
28    let mut parts = Vec::new();
29    for part in path.components() {
30        match part {
31            Component::Normal(p) => parts.push(p.to_string_lossy().into_owned()),
32            Component::CurDir => {}
33            Component::ParentDir => {
34                if parts.pop().is_none() {
35                    bail!("Module import escapes package");
36                }
37            }
38            _ => bail!("Module path must be package-relative"),
39        }
40    }
41    Ok(parts.join("/"))
42}
43/// Resolves a package-relative import the same way when collecting the
44/// module sources and when compiling them to browser addresses.
45pub fn imported_module(
46    from: &Path,
47    specifier: &str,
48    exists: impl Fn(&str) -> bool,
49) -> Result<String> {
50    let parent = from.parent().unwrap_or(Path::new(""));
51    let requested = normalized(&parent.join(specifier))?;
52    ["", ".tsx", ".ts", ".js"]
53        .into_iter()
54        .map(|suffix| format!("{requested}{suffix}"))
55        .find(|path| exists(path))
56        .ok_or_else(|| anyhow!("{}: missing package module {specifier}", from.display()))
57}
58impl Browser {
59    /// The package `descriptor` describes, with every module compiled and its
60    /// relative imports rewritten to addresses under `base`. An error when a
61    /// path is noncanonical, an import is missing, or a widget is misnamed,
62    /// missing or replaces a built-in.
63    pub fn new(descriptor: &Value, base: &str) -> Result<Self> {
64        let sources: BTreeMap<String, String> =
65            serde_json::from_value(descriptor.get("modules").cloned().unwrap_or(json!({})))?;
66        let widgets: BTreeMap<String, String> =
67            serde_json::from_value(descriptor.get("widgets").cloned().unwrap_or(json!({})))?;
68        let styles: BTreeMap<String, String> =
69            serde_json::from_value(descriptor.get("styles").cloned().unwrap_or(json!({})))?;
70        let mut hash = Sha256::new();
71        hash.update(crate::addresses::BUILD);
72        hash.update(serde_json::to_vec(&json!([sources, widgets, styles]))?);
73        let digest = format!("{:x}", hash.finalize());
74        let prefix = format!("{base}browser/{digest}/");
75        let mut modules = BTreeMap::new();
76        for (path, source) in &sources {
77            if normalized(Path::new(path))? != *path {
78                bail!("Noncanonical package module {path}");
79            }
80            let mut imports = BTreeMap::new();
81            for specifier in crate::widgets::extension_imports(Path::new(path), source) {
82                let target =
83                    imported_module(Path::new(path), &specifier, |p| sources.contains_key(p))?;
84                imports.insert(specifier, format!("{prefix}modules/{target}"));
85            }
86            let js = crate::widgets::compile_extension(Path::new(path), source, &[], &imports)
87                .map_err(|e| anyhow!("{path}: {e:#}"))?;
88            modules.insert(path.clone(), js);
89        }
90        for path in styles.keys() {
91            if normalized(Path::new(path))? != *path {
92                bail!("Noncanonical package style {path}");
93            }
94        }
95        for (name, path) in &widgets {
96            if !name.starts_with(char::is_uppercase)
97                || !name.chars().all(|c| c.is_alphanumeric() || c == '_')
98            {
99                bail!("Invalid package widget name {name}");
100            }
101            if !modules.contains_key(path) {
102                bail!("Widget {name} module {path} missing");
103            }
104            if crate::widgets::SYSTEM.iter().any(|(n, _)| n == name) {
105                bail!("Package widget {name} replaces a built-in");
106            }
107        }
108        Ok(Self {
109            digest,
110            modules,
111            widgets,
112            styles,
113        })
114    }
115    /// Each widget's module address under `base`, by widget name.
116    pub fn widgets(&self, base: &str) -> BTreeMap<String, String> {
117        self.widgets
118            .iter()
119            .map(|(n, p)| {
120                (
121                    n.clone(),
122                    format!("{base}browser/{}/modules/{p}", self.digest),
123                )
124            })
125            .collect()
126    }
127    /// Every stylesheet's address under `base`.
128    pub fn styles(&self, base: &str) -> Vec<String> {
129        self.styles
130            .keys()
131            .map(|p| format!("{base}browser/{}/styles/{p}", self.digest))
132            .collect()
133    }
134    /// The response to `path`, relative to the extension's base: a compiled
135    /// module or a stylesheet. `None` when `path` names neither, or an older
136    /// digest.
137    pub fn response(&self, path: &str) -> Option<Value> {
138        let path = path.strip_prefix(&format!("browser/{}/", self.digest))?;
139        let (source, mime) = if let Some(name) = path.strip_prefix("modules/") {
140            (self.modules.get(name)?, "text/javascript")
141        } else {
142            let name = path.strip_prefix("styles/")?;
143            (self.styles.get(name)?, "text/css")
144        };
145        Some(json!({"body":source,"mime":mime,"status":200}))
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152    #[test]
153    fn package_modules_use_the_widget_compiler_and_own_relative_imports() {
154        let descriptor = json!({"widgets":{"Tool":"Tool.tsx"},"modules":{
155            "Tool.tsx":"import React from 'react'; import {label} from './text'; export default function Tool(){return <div>{label}</div>}",
156            "text.ts":"export const label='A tool';"
157        },"styles":{"tool.css":".example {color:inherit}"}});
158        let browser =
159            Browser::new(&descriptor, "/mounted/__devpage/extensions/owner/toy/").unwrap();
160        let url = browser.widgets("/mounted/__devpage/extensions/owner/toy/")["Tool"].clone();
161        let suffix = url.split("/toy/").nth(1).unwrap();
162        let response = browser.response(suffix).unwrap();
163        let js = response["body"].as_str().unwrap();
164        assert!(js.contains("react/jsx-runtime"));
165        assert!(js.contains("/modules/text.ts"));
166        assert!(!js.contains(r#"from "./text""#));
167        assert_eq!(browser.styles("/base/").len(), 1);
168        assert!(browser.response("browser/wrong/modules/Tool.tsx").is_none());
169        assert!(Browser::new(&json!({"widgets":{"Tool":"missing.tsx"}}), "/").is_err());
170        assert!(
171            Browser::new(
172                &json!({"modules":{"../outside.ts":"export default 1;"}}),
173                "/"
174            )
175            .is_err()
176        );
177        assert!(
178            Browser::new(
179                &json!({"modules":{"Tool.tsx":"import './missing'; export default ()=>null;"}}),
180                "/"
181            )
182            .is_err()
183        );
184    }
185}