use std::{
fmt::Write as _,
fs,
net::SocketAddr,
path::{Path, PathBuf},
process::{Command, Stdio},
time::Duration,
};
use anyhow::{Context as _, bail};
use sha2::{Digest as _, Sha256};
use crate::{
build::Built,
package::{AppConfig, PackageOptions},
runtime::{self, WebRuntime},
ui,
};
const PAGE: &str = include_str!("web/index.html");
const DEV_PAGE: &str = include_str!("web/dev.html");
const UI_SETS: &[&str] = &["nsh/ui/mobile"];
const CODE: (&str, &str) = ("app", "nshc");
const DIGEST_LEN: usize = 10;
const PORT: u16 = 4173;
pub(crate) fn package(
options: &PackageOptions<'_>,
config: &AppConfig,
name: &str,
id: &str,
built: &Built,
) -> anyhow::Result<()> {
if crate::rust_app::current().is_some() {
bail!("apps with Rust components of their own cannot be packaged for the web yet");
}
let missing: Vec<&str> = built
.ui_sets
.iter()
.map(String::as_str)
.filter(|set| !UI_SETS.contains(set))
.collect();
if !missing.is_empty() {
bail!(
"the web runtime has no {}, which the app imports",
missing.join(", ")
);
}
let runtime = runtime::web(runtime::WebKind::Release, true)?.context("no web runtime")?;
let dir = options.out.join(name);
let step = ui::Step::start(format!("packaging {}", ui::path(&dir)));
if dir.exists() {
fs::remove_dir_all(&dir).with_context(|| format!("remove {}", dir.display()))?;
}
let site = Site::new(&dir)?;
let js = fs::read_to_string(&runtime.js)
.with_context(|| format!("read {}", runtime.js.display()))?;
let js = nsh_bundler::minify_module("nsh.js", &js).map_err(anyhow::Error::msg)?;
let js = site.add("nsh.js", js.as_bytes())?;
let wasm = site.add(
"nsh.wasm",
&fs::read(&runtime.wasm).with_context(|| format!("read {}", runtime.wasm.display()))?,
)?;
let code = site.add(&format!("{}.{}", CODE.0, CODE.1), &built.bytecode)?;
let harden = site.add("harden.nshc", &nsh_js::compile_harden()?)?;
let mut chunks = serde_json::Map::new();
for chunk in &built.chunks {
let stem = chunk.id.strip_suffix(".js").unwrap_or(&chunk.id);
let url = site.add(&format!("chunks/{stem}.{}", CODE.1), &chunk.bytecode)?;
chunks.insert(chunk.id.clone(), url.into());
}
let mut assets = serde_json::Map::new();
let mut fonts = Vec::new();
for asset in &built.assets {
let bytes = fs::read(&asset.source).with_context(|| format!("read {}", asset.path))?;
let url = site.add(&format!("assets/{}", asset.path), &bytes)?;
if is_font(&asset.path) {
fonts.push(asset.path.clone());
}
assets.insert(asset.path.clone(), url.into());
}
let icons = match &config.icon {
Some(icon) => Icons::write(&site, icon)?,
None => Icons::default(),
};
let (fonts, chunk_fonts) = font_loads(&fonts, &built.code, &built.chunks);
let appearance = Appearance::of(config);
fs::write(
dir.join("manifest.webmanifest"),
manifest(name, id, appearance, &icons),
)?;
let app = serde_json::json!({
"wasm": wasm,
"code": code,
"harden": harden,
"capabilities": built.capabilities_json(),
"assets": assets,
"fonts": fonts,
"chunkFonts": chunk_fonts,
"chunks": chunks,
});
let html = page(&PageParts {
name,
appearance,
icons: &icons,
runtime: &js,
wasm: &wasm,
code: &code,
harden: &harden,
fonts: &fonts
.iter()
.map(|path| assets[path].as_str().unwrap_or_default().to_owned())
.collect::<Vec<_>>(),
app: &app,
connect: connect_src(built.capabilities.as_ref()).as_deref(),
});
fs::write(dir.join("index.html"), html)?;
step.done(format!(
"packaged {}{}",
ui::path(&dir),
ui::dim(format!(", {}", ui::bytes(dir_size(&dir))))
));
if options.run {
serve(&dir)?;
}
Ok(())
}
fn serve(dir: &Path) -> anyhow::Result<()> {
let mut server = None;
for port in (PORT..PORT + 10).chain([0]) {
if let Ok(s) =
nsh_dev::SiteServer::start(SocketAddr::from(([127, 0, 0, 1], port)), dir.into())
{
server = Some(s);
break;
}
}
let server = server.context("no free port to serve the site on")?;
let url = format!("http://127.0.0.1:{}/", server.local_addr().port());
ui::note(format!("serving {} at {url}", ui::path(dir)));
open_browser(&url);
let _stoppable = ui::Stoppable::new();
while !ui::stop_requested() {
std::thread::sleep(Duration::from_millis(200));
}
Ok(())
}
pub(crate) fn open_browser(url: &str) {
let mut command = if cfg!(target_os = "macos") {
Command::new("open")
} else if cfg!(windows) {
let mut c = Command::new("cmd");
c.args(["/C", "start", ""]);
c
} else {
Command::new("xdg-open")
};
let opened = command
.arg(url)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.is_ok();
if !opened {
ui::warn(format!("cannot open a browser: open {url}"));
}
}
pub(crate) type Files = Vec<(String, Vec<u8>)>;
pub(crate) fn dev_host(runtime: &WebRuntime) -> anyhow::Result<(String, Files)> {
let read = |path: &Path| fs::read(path).with_context(|| format!("read {}", path.display()));
let ui_sets = serde_json::to_string(UI_SETS)?;
let page = DEV_PAGE
.replace(
"{{protocol}}",
&nsh_dev::protocol::PROTOCOL_VERSION.to_string(),
)
.replace("{{ui_sets}}", &ui_sets);
Ok((
page,
vec![
("nsh.js".to_owned(), read(&runtime.js)?),
("nsh.wasm".to_owned(), read(&runtime.wasm)?),
],
))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Appearance {
Light,
Dark,
System,
}
impl Appearance {
fn of(config: &AppConfig) -> Appearance {
match config.appearance.as_deref() {
Some("light") => Appearance::Light,
Some("dark") => Appearance::Dark,
_ => Appearance::System,
}
}
fn colors(self) -> (&'static str, &'static str) {
match self {
Appearance::Light => (LIGHT, LIGHT),
Appearance::Dark => (DARK, DARK),
Appearance::System => (LIGHT, DARK),
}
}
}
const LIGHT: &str = "#ffffff";
const DARK: &str = "#000000";
struct Site {
dir: PathBuf,
}
impl Site {
fn new(dir: &Path) -> anyhow::Result<Site> {
fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
Ok(Site { dir: dir.into() })
}
fn add(&self, path: &str, bytes: &[u8]) -> anyhow::Result<String> {
let name = hashed_name(path, bytes);
let file = self.dir.join(&name);
if let Some(parent) = file.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&file, bytes).with_context(|| format!("write {}", file.display()))?;
Ok(url_path(&name))
}
}
fn hashed_name(path: &str, bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
let mut hex = String::with_capacity(DIGEST_LEN);
for byte in digest.iter().take(DIGEST_LEN.div_ceil(2)) {
let _ = write!(hex, "{byte:02x}");
}
hex.truncate(DIGEST_LEN);
let (dir, file) = match path.rsplit_once('/') {
Some((dir, file)) => (format!("{dir}/"), file),
None => (String::new(), path),
};
match file.rsplit_once('.') {
Some((stem, ext)) if !stem.is_empty() => format!("{dir}{stem}.{hex}.{ext}"),
_ => format!("{dir}{file}.{hex}"),
}
}
fn url_path(path: &str) -> String {
let mut out = String::with_capacity(path.len());
for byte in path.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' | b'@' => {
out.push(byte as char)
}
_ => {
let _ = write!(out, "%{byte:02X}");
}
}
}
out
}
fn font_loads(
fonts: &[String],
entry: &str,
chunks: &[crate::build::BuiltChunk],
) -> (Vec<String>, serde_json::Map<String, serde_json::Value>) {
let mut eager = Vec::new();
let mut by_chunk = serde_json::Map::new();
for font in fonts {
let uri = format!("asset:/{font}");
let users: Vec<&crate::build::BuiltChunk> =
chunks.iter().filter(|c| c.code.contains(&uri)).collect();
if entry.contains(&uri) || users.is_empty() {
eager.push(font.clone());
continue;
}
for chunk in users {
let list = by_chunk
.entry(chunk.id.clone())
.or_insert_with(|| serde_json::Value::Array(Vec::new()));
if let serde_json::Value::Array(list) = list {
list.push(font.clone().into());
}
}
}
(eager, by_chunk)
}
fn is_font(path: &str) -> bool {
let ext = path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc"))
}
#[derive(Default)]
struct Icons {
favicon: Option<String>,
touch: Option<String>,
manifest: Vec<(u32, String)>,
}
impl Icons {
fn write(site: &Site, icon: &Path) -> anyhow::Result<Icons> {
let image = image::open(icon).with_context(|| format!("read {}", icon.display()))?;
let png = |size: u32| -> anyhow::Result<String> {
let scaled = image.resize_to_fill(size, size, image::imageops::FilterType::Lanczos3);
let mut bytes = Vec::new();
scaled
.write_to(
&mut std::io::Cursor::new(&mut bytes),
image::ImageFormat::Png,
)
.context("encode the icon")?;
site.add(&format!("icons/{size}.png"), &bytes)
};
Ok(Icons {
favicon: Some(png(32)?),
touch: Some(png(180)?),
manifest: vec![(192, png(192)?), (512, png(512)?)],
})
}
}
fn manifest(name: &str, id: &str, appearance: Appearance, icons: &Icons) -> String {
let (light, dark) = appearance.colors();
let background = if appearance == Appearance::Dark {
dark
} else {
light
};
let icons: Vec<_> = icons
.manifest
.iter()
.map(|(size, url)| {
serde_json::json!({ "src": url, "sizes": format!("{size}x{size}"), "type": "image/png" })
})
.collect();
let manifest = serde_json::json!({
"id": id,
"name": name,
"short_name": name,
"start_url": "./",
"scope": "./",
"display": "standalone",
"background_color": background,
"theme_color": background,
"icons": icons,
});
serde_json::to_string_pretty(&manifest).unwrap_or_default()
}
fn connect_src(capabilities: Option<&nsh_core::access::Capabilities>) -> Option<String> {
let network = &capabilities?.network;
let patterns = network
.hosts
.iter()
.chain(network.http.iter().map(|grant| &grant.host))
.map(nsh_core::access::HostPattern::as_str);
let mut sources = vec!["'self'".to_owned()];
for pattern in patterns {
if pattern == "*" {
return None;
}
let source = if pattern.ends_with(']') || !pattern.contains(':') {
format!("{pattern}:*")
} else {
pattern.to_owned()
};
if !sources.contains(&source) {
sources.push(source);
}
}
Some(sources.join(" "))
}
struct PageParts<'a> {
name: &'a str,
appearance: Appearance,
icons: &'a Icons,
runtime: &'a str,
wasm: &'a str,
code: &'a str,
harden: &'a str,
fonts: &'a [String],
app: &'a serde_json::Value,
connect: Option<&'a str>,
}
fn page(parts: &PageParts<'_>) -> String {
let (light, dark) = parts.appearance.colors();
let mut head = String::new();
if let Some(sources) = parts.connect {
let _ = writeln!(
head,
"<meta http-equiv=\"Content-Security-Policy\" content=\"connect-src {sources}\">"
);
}
match parts.appearance {
Appearance::System => {
let _ = writeln!(
head,
"<meta name=\"color-scheme\" content=\"light dark\">\n\
<meta name=\"theme-color\" content=\"{light}\" media=\"(prefers-color-scheme: light)\">\n\
<meta name=\"theme-color\" content=\"{dark}\" media=\"(prefers-color-scheme: dark)\">"
);
}
Appearance::Light | Appearance::Dark => {
let scheme = if parts.appearance == Appearance::Dark {
"dark"
} else {
"light"
};
let _ = writeln!(
head,
"<meta name=\"color-scheme\" content=\"{scheme}\">\n\
<meta name=\"theme-color\" content=\"{light}\">"
);
}
}
let _ = writeln!(
head,
"<link rel=\"manifest\" href=\"manifest.webmanifest\">"
);
if let Some(favicon) = &parts.icons.favicon {
let _ = writeln!(
head,
"<link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"{favicon}\">"
);
}
if let Some(touch) = &parts.icons.touch {
let _ = writeln!(head, "<link rel=\"apple-touch-icon\" href=\"{touch}\">");
}
for url in [parts.wasm, parts.code, parts.harden]
.into_iter()
.chain(parts.fonts.iter().map(String::as_str))
{
let _ = writeln!(
head,
"<link rel=\"preload\" href=\"{url}\" as=\"fetch\" crossorigin>"
);
}
let app = parts.app.to_string().replace("</", "<\\/");
let colors = |background: &str| {
let text = if background == DARK {
"#f2f2f7"
} else {
"#1c1c1e"
};
format!("html, body {{ background: {background}; color: {text}; }}")
};
let colors = match parts.appearance {
Appearance::System => format!(
" {}\n @media (prefers-color-scheme: dark) {{ {} }}",
colors(light),
colors(dark)
),
Appearance::Light | Appearance::Dark => format!(" {}", colors(light)),
};
PAGE.replace("{{title}}", &escape_html(parts.name))
.replace("{{head}}", head.trim_end())
.replace("{{colors}}", &colors)
.replace("{{runtime}}", parts.runtime)
.replace("{{app}}", &app)
}
fn escape_html(text: &str) -> String {
text.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
fn dir_size(dir: &Path) -> usize {
let Ok(entries) = fs::read_dir(dir) else {
return 0;
};
entries
.flatten()
.map(|entry| match entry.file_type() {
Ok(t) if t.is_dir() => dir_size(&entry.path()),
_ => entry.metadata().map_or(0, |m| m.len() as usize),
})
.sum()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_carry_the_digest_of_the_content() {
let a = hashed_name("assets/img/logo@2x.png", b"one");
assert!(a.starts_with("assets/img/logo@2x."), "{a}");
assert!(a.ends_with(".png"), "{a}");
assert_eq!(a.len(), "assets/img/logo@2x..png".len() + DIGEST_LEN);
assert_eq!(a, hashed_name("assets/img/logo@2x.png", b"one"));
assert_ne!(a, hashed_name("assets/img/logo@2x.png", b"two"));
assert_eq!(
hashed_name("LICENSE", b"x").len(),
"LICENSE.".len() + DIGEST_LEN
);
assert!(hashed_name(".env", b"x").starts_with(".env."));
}
#[test]
fn urls_escape_what_names_may_hold() {
assert_eq!(url_path("assets/a b/中.png"), "assets/a%20b/%E4%B8%AD.png");
assert_eq!(url_path("assets/@nsh-ui/x.ttf"), "assets/@nsh-ui/x.ttf");
}
#[test]
fn the_page_names_the_files_and_cannot_be_broken_out_of() {
let app = serde_json::json!({ "code": "app.1.nshc", "x": "</script><b>" });
let html = page(&PageParts {
name: "A <b> & \"c\"",
appearance: Appearance::System,
icons: &Icons::default(),
runtime: "nsh.0123456789.js",
wasm: "nsh.0123456789.wasm",
code: "app.1.nshc",
harden: "harden.2.nshc",
fonts: &["assets/f.1.ttf".to_owned()],
app: &app,
connect: Some("'self' api.example.com:*"),
});
assert!(html.contains("<title>A <b> & "c"</title>"));
assert!(html.contains("from \"./nsh.0123456789.js\""));
assert!(html.contains("<link rel=\"preload\" href=\"assets/f.1.ttf\""));
assert!(html.contains("<link rel=\"preload\" href=\"harden.2.nshc\""));
assert!(html.contains("media=\"(prefers-color-scheme: dark)\""));
assert!(!html.contains("</script><b>"));
assert!(!html.contains("{{"), "{html}");
assert!(html.contains(
"<meta http-equiv=\"Content-Security-Policy\" content=\"connect-src 'self' api.example.com:*\">"
));
}
#[test]
fn requests_are_limited_to_the_declared_hosts() {
let caps =
|json: serde_json::Value| nsh_core::access::Capabilities::from_json(&json).unwrap();
assert_eq!(connect_src(None), None);
assert_eq!(
connect_src(Some(&caps(serde_json::json!({ "clipboard": true })))).as_deref(),
Some("'self'")
);
let declared = caps(serde_json::json!({ "network": {
"hosts": ["api.example.com", "*.cdn.example.com", "localhost:8080"],
"http": [{ "host": "api.example.com", "methods": ["GET"] }],
} }));
assert_eq!(
connect_src(Some(&declared)).as_deref(),
Some("'self' api.example.com:* *.cdn.example.com:* localhost:8080")
);
let any = caps(serde_json::json!({ "network": { "hosts": ["*"] } }));
assert_eq!(connect_src(Some(&any)), None);
}
#[test]
fn fonts_only_chunks_register_come_with_them() {
let chunk = |id: &str, code: &str| crate::build::BuiltChunk {
id: id.to_owned(),
code: code.to_owned(),
bytecode: Vec::new(),
source_map: None,
};
let fonts = ["a.ttf", "b.ttf", "@ui/c.ttf"].map(String::from);
let chunks = [
chunk(
"Text.js",
"font(`asset:/b.ttf`, `B`); font(`asset:/a.ttf`, `A`)",
),
chunk("Other.js", "font(`asset:/b.ttf`, `B`)"),
];
let (eager, by_chunk) = font_loads(&fonts, "font(`asset:/a.ttf`, `A`)", &chunks);
assert_eq!(eager, ["a.ttf", "@ui/c.ttf"]);
assert_eq!(
serde_json::Value::Object(by_chunk),
serde_json::json!({ "Text.js": ["b.ttf"], "Other.js": ["b.ttf"] })
);
}
#[test]
fn manifests_follow_the_appearance() {
let icons = Icons {
manifest: vec![(192, "icons/192.a.png".to_owned())],
..Icons::default()
};
let json: serde_json::Value = serde_json::from_str(&manifest(
"Demo",
"com.example.demo",
Appearance::Dark,
&icons,
))
.unwrap();
assert_eq!(json["background_color"], "#000000");
assert_eq!(json["display"], "standalone");
assert_eq!(json["icons"][0]["sizes"], "192x192");
}
}