use serde_json::{Map, Value, json};
use super::Registry;
pub const FORMAT: u32 = 2;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportKind {
Component,
Module,
Function,
Class,
Value,
}
impl ExportKind {
pub fn as_str(self) -> &'static str {
match self {
ExportKind::Component => "component",
ExportKind::Module => "module",
ExportKind::Function => "function",
ExportKind::Class => "class",
ExportKind::Value => "value",
}
}
pub fn parse(name: &str) -> Option<ExportKind> {
Some(match name {
"component" => ExportKind::Component,
"module" => ExportKind::Module,
"function" => ExportKind::Function,
"class" => ExportKind::Class,
"value" => ExportKind::Value,
_ => return None,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExportDescription {
pub name: String,
pub kind: ExportKind,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssetDescription {
pub path: String,
pub source: String,
pub targets: Vec<crate::platform::Os>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetDescription {
pub specifier: String,
pub exports: Vec<ExportDescription>,
pub declarations: String,
pub reexported_values: Vec<String>,
pub reexported_types: Vec<String>,
pub native_values: Vec<String>,
pub assets: Vec<AssetDescription>,
pub undocumented: Vec<String>,
}
impl SetDescription {
pub fn of(registry: &Registry) -> Option<SetDescription> {
let specifier = registry.specifier()?;
let specs = registry.specs();
let modules = registry.module_specs();
let mut exports: Vec<ExportDescription> = Vec::new();
let mut add = |name: &str, kind: ExportKind| {
if !exports.iter().any(|e| e.name == name) {
exports.push(ExportDescription {
name: name.to_owned(),
kind,
});
}
};
for spec in &specs {
add(&spec.export, ExportKind::Component);
}
for m in &modules {
if specs.iter().any(|s| s.export == m.name)
|| (!m.flat && registry.function_members(m.name).is_some())
{
continue;
}
if m.flat {
for f in &m.functions {
add(f.name, ExportKind::Function);
}
} else {
add(m.name, ExportKind::Module);
}
}
for class in registry.class_specs() {
add(class.name, ExportKind::Class);
}
let (values, types) = registry.reexports();
for value in values.iter().chain(registry.native_value_names()) {
add(value, ExportKind::Value);
}
let strings = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect();
Some(SetDescription {
specifier: specifier.to_owned(),
exports,
declarations: super::declarations(registry, &[]),
reexported_values: strings(values),
reexported_types: strings(types),
native_values: strings(registry.native_value_names()),
assets: registry
.scoped_asset_files()
.filter_map(|(targets, file)| {
Some(AssetDescription {
path: file.path().to_owned(),
source: file.source?.to_owned(),
targets: targets.to_vec(),
})
})
.collect(),
undocumented: registry.undocumented(),
})
}
pub fn exports_of(&self, kind: ExportKind) -> impl Iterator<Item = &str> {
self.exports
.iter()
.filter(move |e| e.kind == kind)
.map(|e| e.name.as_str())
}
fn to_value(&self) -> Value {
json!({
"specifier": self.specifier,
"exports": self.exports.iter().map(|e| json!({
"name": e.name,
"kind": e.kind.as_str(),
})).collect::<Vec<_>>(),
"declarations": self.declarations,
"reexports": {
"values": self.reexported_values,
"types": self.reexported_types,
},
"native_values": self.native_values,
"assets": self.assets.iter().map(|a| json!({
"path": a.path,
"source": a.source,
"targets": a.targets.iter().map(|t| t.name()).collect::<Vec<_>>(),
})).collect::<Vec<_>>(),
"undocumented": self.undocumented,
})
}
fn from_value(value: &Value, at: &str) -> Result<SetDescription, String> {
let set = object(value, at)?;
let specifier = string(set, "specifier", at)?;
if specifier.is_empty() {
return Err(format!("{at}.specifier is empty"));
}
let at = format!("{at} ({specifier})");
let exports = array(set, "exports", &at)?
.iter()
.enumerate()
.map(|(i, e)| {
let at = format!("{at}.exports[{i}]");
let e = object(e, &at)?;
let kind = string(e, "kind", &at)?;
Ok(ExportDescription {
name: string(e, "name", &at)?,
kind: ExportKind::parse(&kind)
.ok_or_else(|| format!("{at}.kind: unknown kind {kind:?}"))?,
})
})
.collect::<Result<Vec<_>, String>>()?;
let reexports = object(
set.get("reexports")
.ok_or_else(|| format!("{at}: no reexports"))?,
&format!("{at}.reexports"),
)?;
let assets = array(set, "assets", &at)?
.iter()
.enumerate()
.map(|(i, a)| {
let at = format!("{at}.assets[{i}]");
let a = object(a, &at)?;
let targets = match a.get("targets") {
None => Vec::new(),
Some(_) => strings(a, "targets", &at)?
.iter()
.map(|name| {
crate::platform::Os::from_name(name)
.ok_or_else(|| format!("{at}: unknown target {name}"))
})
.collect::<Result<Vec<_>, String>>()?,
};
Ok(AssetDescription {
path: string(a, "path", &at)?,
source: string(a, "source", &at)?,
targets,
})
})
.collect::<Result<Vec<_>, String>>()?;
Ok(SetDescription {
specifier,
exports,
declarations: string(set, "declarations", &at)?,
reexported_values: strings(reexports, "values", &format!("{at}.reexports"))?,
reexported_types: strings(reexports, "types", &format!("{at}.reexports"))?,
native_values: strings(set, "native_values", &at)?,
assets,
undocumented: strings(set, "undocumented", &at)?,
})
}
}
impl From<&Registry> for SetDescription {
#[track_caller]
fn from(registry: &Registry) -> Self {
let set = SetDescription::of(registry).expect("a UI set: a registry with a specifier");
let unknown: Vec<&str> = registry
.asset_files()
.filter(|file| file.source.is_none())
.map(|file| file.uri)
.collect();
assert!(
unknown.is_empty(),
"{}: this build of UI set {} kept no path of {}; describe UI sets in a \
development build or with nsh-core's `declarations` feature",
unknown.join(", "),
set.specifier,
if unknown.len() == 1 {
"the file"
} else {
"these files"
},
);
set
}
}
impl From<Registry> for SetDescription {
#[track_caller]
fn from(registry: Registry) -> Self {
SetDescription::from(®istry)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Description {
pub nsh: String,
pub sets: Vec<SetDescription>,
}
impl Description {
#[track_caller]
pub fn of(sets: &[Registry]) -> Description {
Description {
nsh: VERSION.to_owned(),
sets: sets
.iter()
.flat_map(Registry::sets)
.map(SetDescription::from)
.collect(),
}
}
pub fn to_json(&self) -> String {
json!({
"format": FORMAT,
"nsh": self.nsh,
"sets": self.sets.iter().map(SetDescription::to_value).collect::<Vec<_>>(),
})
.to_string()
}
pub fn from_json(text: &str) -> Result<Description, String> {
let value: Value = serde_json::from_str(text).map_err(|e| format!("not JSON: {e}"))?;
let doc = object(&value, "the description")?;
let format = doc
.get("format")
.and_then(Value::as_u64)
.ok_or("the description has no format")?;
if format != u64::from(FORMAT) {
return Err(format!(
"the description is in format {format}, and this nsh reads format {FORMAT}"
));
}
let sets = array(doc, "sets", "the description")?
.iter()
.enumerate()
.map(|(i, set)| SetDescription::from_value(set, &format!("sets[{i}]")))
.collect::<Result<Vec<_>, String>>()?;
Ok(Description {
nsh: string(doc, "nsh", "the description")?,
sets,
})
}
}
fn object<'v>(value: &'v Value, at: &str) -> Result<&'v Map<String, Value>, String> {
value
.as_object()
.ok_or_else(|| format!("{at} is not an object"))
}
fn string(object: &Map<String, Value>, key: &str, at: &str) -> Result<String, String> {
object
.get(key)
.and_then(Value::as_str)
.map(str::to_owned)
.ok_or_else(|| format!("{at}: no string {key}"))
}
fn array<'v>(object: &'v Map<String, Value>, key: &str, at: &str) -> Result<&'v [Value], String> {
object
.get(key)
.and_then(Value::as_array)
.map(Vec::as_slice)
.ok_or_else(|| format!("{at}: no list {key}"))
}
fn strings(object: &Map<String, Value>, key: &str, at: &str) -> Result<Vec<String>, String> {
array(object, key, at)?
.iter()
.map(|v| {
v.as_str()
.map(str::to_owned)
.ok_or_else(|| format!("{at}.{key}: not a list of strings"))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::prelude::*;
#[component]
fn Badge() -> impl IntoElement {
view()
}
#[component]
fn Plain() -> impl IntoElement {
view()
}
fn set() -> Registry {
let mut r = Registry::ui_set("test/description");
r.register::<Badge>();
r.reexport(&["safeArea"], &["Insets"]);
r.native_values(&["Stack"]);
r
}
#[test]
fn a_set_is_described_by_its_exports_and_declarations() {
let set = SetDescription::of(&set()).unwrap();
assert_eq!(set.specifier, "test/description");
let exports: Vec<(&str, ExportKind)> = set
.exports
.iter()
.map(|e| (e.name.as_str(), e.kind))
.collect();
assert_eq!(
exports,
[
("Badge", ExportKind::Component),
("safeArea", ExportKind::Value),
("Stack", ExportKind::Value),
]
);
assert_eq!(
set.exports_of(ExportKind::Component).collect::<Vec<_>>(),
["Badge"]
);
assert_eq!(
set.declarations,
crate::element::declarations(&self::set(), &[])
);
assert_eq!(set.reexported_values, ["safeArea"]);
assert_eq!(set.reexported_types, ["Insets"]);
assert_eq!(set.native_values, ["Stack"]);
assert!(set.undocumented.is_empty());
let mut plain = Registry::ui_set("test/plain");
plain.register::<Plain>();
assert_eq!(SetDescription::of(&plain).unwrap().undocumented, ["Plain"]);
assert!(SetDescription::of(&Registry::new()).is_none());
}
#[test]
fn a_description_survives_json() {
let mut description = Description::of(&[set()]);
description.sets[0].assets.push(AssetDescription {
path: "@app/logo@2x.png".into(),
source: "C:\\app\\assets\\logo@2x.png".into(),
targets: Vec::new(),
});
description.sets[0].assets.push(AssetDescription {
path: "@app/zh-CN.json".into(),
source: "C:\\app\\assets\\zh-CN.json".into(),
targets: vec![crate::platform::Os::Web],
});
let json = description.to_json();
assert_eq!(Description::from_json(&json).unwrap(), description);
assert_eq!(description.nsh, VERSION);
}
#[test]
fn an_asset_without_targets_is_for_every_target() {
let mut description = Description::of(&[set()]);
description.sets[0].assets.push(AssetDescription {
path: "@app/logo@2x.png".into(),
source: "/app/assets/logo@2x.png".into(),
targets: Vec::new(),
});
let mut json: Value = serde_json::from_str(&description.to_json()).unwrap();
let asset = json["sets"][0]["assets"][0].as_object_mut().unwrap();
assert!(asset.remove("targets").is_some());
let parsed = Description::from_json(&json.to_string()).unwrap();
assert_eq!(parsed, description);
}
fn set_with_a_file_without_a_path() -> Registry {
use super::super::{AssetFile, AssetKind};
static FILES: &[AssetFile] = &[
AssetFile {
uri: "asset:/@app/a.png",
source: Some("/app/assets/a.png"),
kind: AssetKind::Image,
},
AssetFile {
uri: "asset:/@app/b.png",
source: None,
kind: AssetKind::Image,
},
];
let mut registry = Registry::ui_set("test/paths");
registry.assets(FILES);
registry
}
#[test]
fn a_file_without_a_path_fails_the_description() {
let registry = set_with_a_file_without_a_path();
for describe in [
(|r: &Registry| drop(SetDescription::from(r))) as fn(&Registry),
|r: &Registry| drop(Description::of(std::slice::from_ref(r))),
] {
let panic =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| describe(®istry)))
.unwrap_err();
let message = panic
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| panic.downcast_ref::<&str>().copied())
.unwrap_or_default();
assert!(message.contains("asset:/@app/b.png"), "{message}");
assert!(!message.contains("asset:/@app/a.png"), "{message}");
assert!(message.contains("`declarations`"), "{message}");
}
}
#[test]
fn files_with_a_path_are_described() {
use super::super::{AssetFile, AssetKind};
static FILES: &[AssetFile] = &[AssetFile {
uri: "asset:/@app/a.png",
source: Some("/app/assets/a.png"),
kind: AssetKind::Image,
}];
let mut registry = Registry::ui_set("test/paths");
registry.assets(FILES);
let set = SetDescription::from(®istry);
let described: Vec<_> = set
.assets
.iter()
.map(|a| (a.path.as_str(), a.source.as_str()))
.collect();
assert_eq!(described, [("@app/a.png", "/app/assets/a.png")]);
}
#[test]
fn the_compilers_description_leaves_out_files_without_a_path() {
let set = SetDescription::of(&set_with_a_file_without_a_path()).unwrap();
let described: Vec<_> = set.assets.iter().map(|a| a.path.as_str()).collect();
assert_eq!(described, ["@app/a.png"]);
}
#[test]
fn assets_for_scopes_files_to_targets() {
use super::super::{AssetFile, AssetKind};
use crate::platform::Os;
static ALL: &[AssetFile] = &[AssetFile {
uri: "asset:/@app/a.png",
source: Some("/app/assets/a.png"),
kind: AssetKind::Image,
}];
static WEB: &[AssetFile] = &[AssetFile {
uri: "asset:/@app/zh-CN.json",
source: Some("/app/assets/zh-CN.json"),
kind: AssetKind::File,
}];
let mut registry = Registry::ui_set("test/assets");
registry.assets(ALL).assets_for(&[Os::Web], WEB);
let set = SetDescription::of(®istry).unwrap();
let scoped: Vec<_> = set
.assets
.iter()
.map(|a| (a.path.as_str(), a.targets.as_slice()))
.collect();
assert_eq!(
scoped,
[("@app/a.png", &[][..]), ("@app/zh-CN.json", &[Os::Web][..])]
);
assert_eq!(registry.asset_files().count(), 2);
}
#[test]
fn another_format_or_a_broken_document_is_refused() {
let json = Description::of(&[set()]).to_json();
let mut value: Value = serde_json::from_str(&json).unwrap();
value["format"] = (FORMAT + 1).into();
let error = Description::from_json(&value.to_string()).unwrap_err();
assert!(error.contains(&format!("format {}", FORMAT + 1)), "{error}");
value["format"] = FORMAT.into();
value["sets"][0]["exports"][0]["kind"] = "widget".into();
let error = Description::from_json(&value.to_string()).unwrap_err();
assert!(
error.contains("sets[0] (test/description).exports[0].kind: unknown kind \"widget\""),
"{error}"
);
assert!(
Description::from_json("{")
.unwrap_err()
.starts_with("not JSON")
);
assert!(
Description::from_json("{}")
.unwrap_err()
.contains("no format")
);
}
}