mod docs;
mod emit;
mod validate;
mod export;
#[cfg(test)]
mod tests;
pub use docs::DocsSection;
pub use export::{ExportSection, DEFAULT_EXPORT_SPEC_PATH};
use std::collections::BTreeMap;
use std::fmt;
use std::fs;
use std::path::Path;
use serde::Deserialize;
pub(crate) use validate::{
is_java_or_kotlin_keyword, sanitize_android_package_id, to_pascal_case,
validate_android_package_id, validate_app_id,
validate_non_empty_label, validate_rel_asset_path, validate_rel_path_inner,
validate_shell_choice, validate_single_filename,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ManifestAppInfo {
pub package_name: String,
pub package_version: String,
pub lib_name: String,
}
impl ManifestAppInfo {
pub fn new(package_name: impl Into<String>, package_version: impl Into<String>, lib_name: impl Into<String>) -> Self {
Self {
package_name: package_name.into(),
package_version: package_version.into(),
lib_name: lib_name.into(),
}
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum AppPresenceConfig {
#[default]
Standard,
Accessory,
Adaptive,
}
impl AppPresenceConfig {
pub fn parse(raw: &str) -> Result<Self, ManifestError> {
match raw {
"standard" => Ok(Self::Standard),
"accessory" => Ok(Self::Accessory),
"adaptive" => Ok(Self::Adaptive),
other => Err(ManifestError::InvalidField {
field: "app.presence",
reason: format!("invalid value '{other}' (expected \"standard\", \"accessory\", or \"adaptive\")"),
}),
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Standard => "standard",
Self::Accessory => "accessory",
Self::Adaptive => "adaptive",
}
}
#[must_use]
pub const fn requires_macos_ls_ui_element(self) -> bool {
matches!(self, Self::Accessory | Self::Adaptive)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(untagged)]
pub enum EntitlementValue {
Bool(bool),
String(String),
Array(Vec<String>),
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum AndroidShell {
#[default]
View,
Compose,
}
impl AndroidShell {
pub fn parse(raw: &str) -> Result<Self, ManifestError> {
let trimmed = raw.trim();
if trimmed.eq_ignore_ascii_case("view") {
Ok(Self::View)
} else if trimmed.eq_ignore_ascii_case("compose") {
Ok(Self::Compose)
} else {
Err(ManifestError::InvalidField {
field: "app.shell.android",
reason: format!("invalid shell '{raw}' (expected one of: view, compose)"),
})
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::View => "view",
Self::Compose => "compose",
}
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct AppShellSection {
pub macos: Option<String>,
pub linux: Option<String>,
pub windows: Option<String>,
pub android: Option<AndroidShell>,
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct AppSection {
pub name: Option<String>,
pub id: Option<String>,
pub executable: Option<String>,
pub presence: AppPresenceConfig,
pub width: Option<u32>,
pub height: Option<u32>,
pub multi_scene: bool,
pub pip: bool,
pub shell: AppShellSection,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AppleSection {
pub min_macos: String,
pub min_ios: String,
pub min_ios_explicit: bool,
pub url_schemes: Vec<String>,
pub usage_descriptions: BTreeMap<String, String>,
pub entitlements: BTreeMap<String, EntitlementValue>,
}
impl Default for AppleSection {
fn default() -> Self {
Self {
min_macos: "13.0".to_owned(),
min_ios: "17.0".to_owned(),
min_ios_explicit: false,
url_schemes: Vec::new(),
usage_descriptions: BTreeMap::new(),
entitlements: BTreeMap::new(),
}
}
}
impl AppleSection {
pub fn resolved_rn_min_ios(&self) -> &str {
if self.min_ios_explicit { &self.min_ios } else { "16.0" }
}
pub fn resolved_nitro_min_ios(&self) -> &str {
if self.min_ios_explicit {
let mut parts = self.min_ios.split('.');
let major = parts.next().and_then(|s| s.parse::<u32>().ok()).unwrap_or(16);
let minor = parts.next().and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);
let patch = parts.next().and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);
if (major, minor, patch) <= (16, 0, 0) {
return &self.min_ios;
}
}
"16.0"
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AndroidSection {
pub min_sdk: u32,
pub target_sdk: u32,
pub permissions: Vec<String>,
}
impl Default for AndroidSection {
fn default() -> Self {
Self { min_sdk: 24, target_sdk: 35, permissions: Vec::new() }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WebExtensionSection {
pub name: Option<String>,
pub popup: String,
pub service_worker: String,
pub assets: Vec<String>,
}
impl Default for WebExtensionSection {
fn default() -> Self {
Self {
name: None,
popup: "popup.html".to_owned(),
service_worker: "background.js".to_owned(),
assets: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WebSection {
pub root: String,
pub index: String,
pub extension: Option<WebExtensionSection>,
}
impl Default for WebSection {
fn default() -> Self {
Self { root: "web".to_owned(), index: "index.html".to_owned(), extension: None }
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct NvManifest {
pub app: AppSection,
pub apple: AppleSection,
pub android: AndroidSection,
pub web: WebSection,
pub export: Option<ExportSection>,
pub docs: Option<DocsSection>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ManifestError {
Io(String),
TomlParse(String),
InvalidField { field: &'static str, reason: String },
}
impl fmt::Display for ManifestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(msg) => write!(f, "failed to read nativeview.toml: {msg}"),
Self::TomlParse(msg) => write!(f, "invalid nativeview.toml: {msg}"),
Self::InvalidField { field, reason } => write!(f, "invalid nativeview.toml field '{field}': {reason}"),
}
}
}
impl std::error::Error for ManifestError {}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawNvManifest {
#[serde(default)]
app: RawAppSection,
#[serde(default)]
apple: RawAppleSection,
#[serde(default)]
android: RawAndroidSection,
#[serde(default)]
web: RawWebSection,
#[serde(default)]
export: Option<export::RawExportSection>,
#[serde(default)]
docs: Option<docs::RawDocsSection>,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawAppShellSection {
macos: Option<String>,
linux: Option<String>,
windows: Option<String>,
android: Option<String>,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawAppSection {
name: Option<String>,
id: Option<String>,
executable: Option<String>,
presence: Option<String>,
width: Option<u32>,
height: Option<u32>,
#[serde(default)]
multi_scene: bool,
#[serde(default)]
pip: bool,
#[serde(default)]
shell: RawAppShellSection,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawAppleSection {
min_macos: Option<String>,
min_ios: Option<String>,
#[serde(default)]
url_schemes: Vec<String>,
#[serde(default)]
usage_descriptions: BTreeMap<String, String>,
#[serde(default)]
entitlements: BTreeMap<String, EntitlementValue>,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawAndroidSection {
min_sdk: Option<u32>,
target_sdk: Option<u32>,
#[serde(default)]
permissions: Vec<String>,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawWebExtensionSection {
name: Option<String>,
popup: Option<String>,
service_worker: Option<String>,
#[serde(default)]
assets: Vec<String>,
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawWebSection {
root: Option<String>,
index: Option<String>,
extension: Option<RawWebExtensionSection>,
}
impl NvManifest {
pub fn parse_toml(src: &str) -> Result<Self, ManifestError> {
let raw: RawNvManifest =
toml::from_str(src).map_err(|e| ManifestError::TomlParse(e.to_string()))?;
let presence = match raw.app.presence.as_deref() {
Some(s) => AppPresenceConfig::parse(s)?,
None => AppPresenceConfig::Standard,
};
let name = raw.app.name.as_deref().map(|v| validate_non_empty_label("app.name", v)).transpose()?;
let id = raw.app.id.as_deref().map(|v| validate_app_id("app.id", v)).transpose()?;
let executable = raw
.app
.executable
.as_deref()
.map(|v| validate_single_filename("app.executable", v))
.transpose()?;
if let Some(0) = raw.app.width {
return Err(ManifestError::InvalidField { field: "app.width", reason: "must be >= 1".to_owned() });
}
if let Some(0) = raw.app.height {
return Err(ManifestError::InvalidField { field: "app.height", reason: "must be >= 1".to_owned() });
}
let shell = AppShellSection {
macos: validate_shell_choice("app.shell.macos", raw.app.shell.macos, &["macos", "skia"])?,
linux: validate_shell_choice("app.shell.linux", raw.app.shell.linux, &["gtk", "qt", "skia"])?,
windows: validate_shell_choice("app.shell.windows", raw.app.shell.windows, &["windows", "skia"])?,
android: raw.app.shell.android.as_deref().map(AndroidShell::parse).transpose()?,
};
let mut url_schemes = Vec::with_capacity(raw.apple.url_schemes.len());
for s in raw.apple.url_schemes {
url_schemes.push(validate_non_empty_label("apple.url_schemes", &s)?);
}
let mut usage_descriptions = BTreeMap::new();
for (k, v) in raw.apple.usage_descriptions {
usage_descriptions.insert(
validate_non_empty_label("apple.usage_descriptions", &k)?,
validate_non_empty_label("apple.usage_descriptions", &v)?,
);
}
let mut entitlements = BTreeMap::new();
for (k, v) in raw.apple.entitlements {
let key = validate_non_empty_label("apple.entitlements", &k)?;
let validated_val = match v {
EntitlementValue::Bool(b) => EntitlementValue::Bool(b),
EntitlementValue::String(s) => {
EntitlementValue::String(validate_non_empty_label("apple.entitlements", &s)?)
}
EntitlementValue::Array(items) => {
let mut clean = Vec::with_capacity(items.len());
for item in items {
clean.push(validate_non_empty_label("apple.entitlements", &item)?);
}
EntitlementValue::Array(clean)
}
};
entitlements.insert(key, validated_val);
}
let apple = AppleSection {
min_macos: match raw.apple.min_macos.as_deref() {
Some(v) => emit::validate_apple_version("apple.min_macos", v)?,
None => "13.0".to_owned(),
},
min_ios: match raw.apple.min_ios.as_deref() {
Some(v) => emit::validate_apple_version("apple.min_ios", v)?,
None => "17.0".to_owned(),
},
min_ios_explicit: raw.apple.min_ios.is_some(),
url_schemes,
usage_descriptions,
entitlements,
};
let mut permissions = Vec::with_capacity(raw.android.permissions.len());
for p in raw.android.permissions {
permissions.push(validate_non_empty_label("android.permissions", &p)?);
}
let min_sdk = raw.android.min_sdk.unwrap_or(24);
let target_sdk = raw.android.target_sdk.unwrap_or(35);
if min_sdk == 0 || target_sdk == 0 || min_sdk > target_sdk {
return Err(ManifestError::InvalidField {
field: "android.min_sdk",
reason: format!("must satisfy 1 <= min_sdk ({min_sdk}) <= target_sdk ({target_sdk})"),
});
}
let android = AndroidSection { min_sdk, target_sdk, permissions };
let web_root = match raw.web.root.as_deref() {
Some(v) => validate_rel_path_inner("web.root", v, true)?,
None => "web".to_owned(),
};
let web_index = match raw.web.index.as_deref() {
Some(v) => validate_rel_asset_path("web.index", v)?,
None => "index.html".to_owned(),
};
let extension = match raw.web.extension {
Some(ext) => {
let ext_name = ext
.name
.as_deref()
.map(|v| validate_non_empty_label("web.extension.name", v))
.transpose()?;
let popup = match ext.popup.as_deref() {
Some(v) => validate_rel_asset_path("web.extension.popup", v)?,
None => "popup.html".to_owned(),
};
let service_worker = match ext.service_worker.as_deref() {
Some(v) => validate_rel_asset_path("web.extension.service_worker", v)?,
None => "background.js".to_owned(),
};
let mut assets = Vec::with_capacity(ext.assets.len());
for a in ext.assets {
assets.push(validate_rel_asset_path("web.extension.assets", &a)?);
}
Some(WebExtensionSection { name: ext_name, popup, service_worker, assets })
}
None => None,
};
let export_section = export::parse_export_section(raw.export)?;
let docs_section = docs::parse_docs_section(raw.docs)?;
Ok(Self {
app: AppSection {
name,
id,
executable,
presence,
width: raw.app.width,
height: raw.app.height,
multi_scene: raw.app.multi_scene,
pip: raw.app.pip,
shell,
},
apple,
android,
web: WebSection { root: web_root, index: web_index, extension },
export: export_section,
docs: docs_section,
})
}
pub fn load_file(path: &Path) -> Result<Self, ManifestError> {
let raw = fs::read_to_string(path)
.map_err(|e| ManifestError::Io(format!("{}: {e}", path.display())))?;
Self::parse_toml(&raw)
}
pub fn load_for_dir(manifest_dir: &Path) -> Result<Self, ManifestError> {
let path = manifest_dir.join("nativeview.toml");
if path.is_file() { Self::load_file(&path) } else { Ok(Self::default()) }
}
#[must_use]
pub fn resolved_name(&self, info: &ManifestAppInfo) -> String {
self.app.name.clone().unwrap_or_else(|| info.package_name.clone())
}
#[must_use]
pub fn resolved_id(&self, info: &ManifestAppInfo) -> String {
if let Some(id) = &self.app.id {
return id.clone();
}
let sanitized: String = info
.lib_name
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '.' })
.collect();
let compact: String = sanitized
.split('.')
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join(".");
format!("io.github.nativeview.{}", if compact.is_empty() { "app" } else { &compact })
}
#[must_use]
pub fn resolved_executable(&self, info: &ManifestAppInfo) -> String {
if let Some(exe) = &self.app.executable {
return exe.clone();
}
if let Some(name) = &self.app.name {
let pascal = to_pascal_case(name);
if !pascal.is_empty() {
return pascal;
}
}
info.lib_name.clone()
}
#[must_use]
pub fn requires_macos_app_bundle(&self) -> bool {
!self.apple.usage_descriptions.is_empty()
|| !self.apple.entitlements.is_empty()
|| self.app.presence != AppPresenceConfig::Standard
}
#[must_use]
pub fn emit_macos_info_plist(&self, info: &ManifestAppInfo, bundle_id_override: Option<&str>) -> String {
emit::emit_macos_info_plist(self, info, bundle_id_override)
}
#[must_use]
pub fn emit_ios_info_plist(&self, info: &ManifestAppInfo) -> String {
emit::emit_ios_info_plist(self, info, false)
}
#[must_use]
pub fn emit_ios_sim_info_plist(&self, info: &ManifestAppInfo) -> String {
emit::emit_ios_info_plist(self, info, true)
}
#[must_use]
pub fn emit_apple_entitlements_plist(&self) -> Option<String> {
emit::emit_apple_entitlements_plist(self, false)
}
#[must_use]
pub fn emit_ios_entitlements_plist(&self) -> Option<String> {
emit::emit_apple_entitlements_plist(self, true)
}
pub fn resolved_android_id(&self, info: &ManifestAppInfo) -> Result<String, ManifestError> {
if let Some(explicit) = &self.app.id {
return validate_android_package_id(explicit);
}
let fallback = sanitize_android_package_id(&self.resolved_id(info));
validate_android_package_id(&fallback)
}
#[must_use]
pub fn emit_android_manifest_xml(&self, info: &ManifestAppInfo) -> String {
emit::emit_android_manifest_xml(self, info, AndroidShell::Compose)
}
#[must_use]
pub fn emit_android_manifest_xml_for(&self, info: &ManifestAppInfo, shell: AndroidShell) -> String {
emit::emit_android_manifest_xml(self, info, shell)
}
pub fn emit_web_mv3_manifest_json(&self, info: &ManifestAppInfo) -> Result<String, ManifestError> {
emit::emit_web_mv3_manifest_json(self, info)
}
}