1mod docs;
6mod emit;
7mod validate;
8mod export;
9#[cfg(test)]
10mod tests;
11
12pub use docs::DocsSection;
13pub use export::{ExportSection, DEFAULT_EXPORT_SPEC_PATH};
14
15use std::collections::BTreeMap;
16use std::fmt;
17use std::fs;
18use std::path::Path;
19
20use serde::Deserialize;
21
22pub(crate) use validate::{
23 is_java_or_kotlin_keyword, sanitize_android_package_id, to_pascal_case,
24 validate_android_package_id, validate_app_id,
25 validate_non_empty_label, validate_rel_asset_path, validate_rel_path_inner,
26 validate_shell_choice, validate_single_filename,
27};
28
29#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct ManifestAppInfo {
32 pub package_name: String,
33 pub package_version: String,
34 pub lib_name: String,
35}
36
37impl ManifestAppInfo {
38 pub fn new(package_name: impl Into<String>, package_version: impl Into<String>, lib_name: impl Into<String>) -> Self {
39 Self {
40 package_name: package_name.into(),
41 package_version: package_version.into(),
42 lib_name: lib_name.into(),
43 }
44 }
45}
46
47#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
49pub enum AppPresenceConfig {
50 #[default]
52 Standard,
53 Accessory,
55 Adaptive,
57}
58
59impl AppPresenceConfig {
60 pub fn parse(raw: &str) -> Result<Self, ManifestError> {
61 match raw {
62 "standard" => Ok(Self::Standard),
63 "accessory" => Ok(Self::Accessory),
64 "adaptive" => Ok(Self::Adaptive),
65 other => Err(ManifestError::InvalidField {
66 field: "app.presence",
67 reason: format!("invalid value '{other}' (expected \"standard\", \"accessory\", or \"adaptive\")"),
68 }),
69 }
70 }
71
72 #[must_use]
73 pub const fn as_str(self) -> &'static str {
74 match self {
75 Self::Standard => "standard",
76 Self::Accessory => "accessory",
77 Self::Adaptive => "adaptive",
78 }
79 }
80
81 #[must_use]
82 pub const fn requires_macos_ls_ui_element(self) -> bool {
83 matches!(self, Self::Accessory | Self::Adaptive)
84 }
85}
86
87#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
89#[serde(untagged)]
90pub enum EntitlementValue {
91 Bool(bool),
92 String(String),
93 Array(Vec<String>),
94}
95
96#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
98pub enum AndroidShell {
99 #[default]
101 View,
102 Compose,
104}
105
106impl AndroidShell {
107 pub fn parse(raw: &str) -> Result<Self, ManifestError> {
108 let trimmed = raw.trim();
109 if trimmed.eq_ignore_ascii_case("view") {
110 Ok(Self::View)
111 } else if trimmed.eq_ignore_ascii_case("compose") {
112 Ok(Self::Compose)
113 } else {
114 Err(ManifestError::InvalidField {
115 field: "app.shell.android",
116 reason: format!("invalid shell '{raw}' (expected one of: view, compose)"),
117 })
118 }
119 }
120
121 #[must_use]
122 pub const fn as_str(self) -> &'static str {
123 match self {
124 Self::View => "view",
125 Self::Compose => "compose",
126 }
127 }
128}
129
130#[derive(Debug, Default, Clone, PartialEq, Eq)]
132pub struct AppShellSection {
133 pub macos: Option<String>,
134 pub linux: Option<String>,
135 pub windows: Option<String>,
136 pub android: Option<AndroidShell>,
137}
138
139#[derive(Debug, Default, Clone, PartialEq, Eq)]
141pub struct AppSection {
142 pub name: Option<String>,
143 pub id: Option<String>,
144 pub executable: Option<String>,
145 pub presence: AppPresenceConfig,
146 pub width: Option<u32>,
147 pub height: Option<u32>,
148 pub multi_scene: bool,
149 pub pip: bool,
150 pub shell: AppShellSection,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct AppleSection {
156 pub min_macos: String,
157 pub min_ios: String,
158 pub min_ios_explicit: bool,
160 pub url_schemes: Vec<String>,
161 pub usage_descriptions: BTreeMap<String, String>,
162 pub entitlements: BTreeMap<String, EntitlementValue>,
163}
164
165impl Default for AppleSection {
166 fn default() -> Self {
167 Self {
168 min_macos: "13.0".to_owned(),
169 min_ios: "17.0".to_owned(),
170 min_ios_explicit: false,
171 url_schemes: Vec::new(),
172 usage_descriptions: BTreeMap::new(),
173 entitlements: BTreeMap::new(),
174 }
175 }
176}
177
178impl AppleSection {
179 pub fn resolved_rn_min_ios(&self) -> &str {
183 if self.min_ios_explicit { &self.min_ios } else { "16.0" }
184 }
185
186 pub fn resolved_nitro_min_ios(&self) -> &str {
190 if self.min_ios_explicit {
191 let mut parts = self.min_ios.split('.');
192 let major = parts.next().and_then(|s| s.parse::<u32>().ok()).unwrap_or(16);
193 let minor = parts.next().and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);
194 let patch = parts.next().and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);
195 if (major, minor, patch) <= (16, 0, 0) {
196 return &self.min_ios;
197 }
198 }
199 "16.0"
200 }
201}
202
203#[derive(Debug, Clone, PartialEq, Eq)]
205pub struct AndroidSection {
206 pub min_sdk: u32,
207 pub target_sdk: u32,
208 pub permissions: Vec<String>,
209}
210
211impl Default for AndroidSection {
212 fn default() -> Self {
213 Self { min_sdk: 24, target_sdk: 35, permissions: Vec::new() }
214 }
215}
216
217#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct WebExtensionSection {
220 pub name: Option<String>,
221 pub popup: String,
222 pub service_worker: String,
223 pub assets: Vec<String>,
224}
225
226impl Default for WebExtensionSection {
227 fn default() -> Self {
228 Self {
229 name: None,
230 popup: "popup.html".to_owned(),
231 service_worker: "background.js".to_owned(),
232 assets: Vec::new(),
233 }
234 }
235}
236
237#[derive(Debug, Clone, PartialEq, Eq)]
239pub struct WebSection {
240 pub root: String,
241 pub index: String,
242 pub extension: Option<WebExtensionSection>,
243}
244
245impl Default for WebSection {
246 fn default() -> Self {
247 Self { root: "web".to_owned(), index: "index.html".to_owned(), extension: None }
248 }
249}
250
251#[derive(Debug, Default, Clone, PartialEq, Eq)]
253pub struct NvManifest {
254 pub app: AppSection,
255 pub apple: AppleSection,
256 pub android: AndroidSection,
257 pub web: WebSection,
258 pub export: Option<ExportSection>,
259 pub docs: Option<DocsSection>,
260}
261
262#[derive(Debug, Clone, PartialEq, Eq)]
264pub enum ManifestError {
265 Io(String),
266 TomlParse(String),
267 InvalidField { field: &'static str, reason: String },
268}
269
270impl fmt::Display for ManifestError {
271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272 match self {
273 Self::Io(msg) => write!(f, "failed to read nativeview.toml: {msg}"),
274 Self::TomlParse(msg) => write!(f, "invalid nativeview.toml: {msg}"),
275 Self::InvalidField { field, reason } => write!(f, "invalid nativeview.toml field '{field}': {reason}"),
276 }
277 }
278}
279
280impl std::error::Error for ManifestError {}
281
282#[derive(Debug, Default, Deserialize)]
283#[serde(deny_unknown_fields)]
284struct RawNvManifest {
285 #[serde(default)]
286 app: RawAppSection,
287 #[serde(default)]
288 apple: RawAppleSection,
289 #[serde(default)]
290 android: RawAndroidSection,
291 #[serde(default)]
292 web: RawWebSection,
293 #[serde(default)]
294 export: Option<export::RawExportSection>,
295 #[serde(default)]
296 docs: Option<docs::RawDocsSection>,
297}
298
299#[derive(Debug, Default, Deserialize)]
300#[serde(deny_unknown_fields)]
301struct RawAppShellSection {
302 macos: Option<String>,
303 linux: Option<String>,
304 windows: Option<String>,
305 android: Option<String>,
306}
307
308#[derive(Debug, Default, Deserialize)]
309#[serde(deny_unknown_fields)]
310struct RawAppSection {
311 name: Option<String>,
312 id: Option<String>,
313 executable: Option<String>,
314 presence: Option<String>,
315 width: Option<u32>,
316 height: Option<u32>,
317 #[serde(default)]
318 multi_scene: bool,
319 #[serde(default)]
320 pip: bool,
321 #[serde(default)]
322 shell: RawAppShellSection,
323}
324
325#[derive(Debug, Default, Deserialize)]
326#[serde(deny_unknown_fields)]
327struct RawAppleSection {
328 min_macos: Option<String>,
329 min_ios: Option<String>,
330 #[serde(default)]
331 url_schemes: Vec<String>,
332 #[serde(default)]
333 usage_descriptions: BTreeMap<String, String>,
334 #[serde(default)]
335 entitlements: BTreeMap<String, EntitlementValue>,
336}
337
338#[derive(Debug, Default, Deserialize)]
339#[serde(deny_unknown_fields)]
340struct RawAndroidSection {
341 min_sdk: Option<u32>,
342 target_sdk: Option<u32>,
343 #[serde(default)]
344 permissions: Vec<String>,
345}
346
347#[derive(Debug, Default, Deserialize)]
348#[serde(deny_unknown_fields)]
349struct RawWebExtensionSection {
350 name: Option<String>,
351 popup: Option<String>,
352 service_worker: Option<String>,
353 #[serde(default)]
354 assets: Vec<String>,
355}
356
357#[derive(Debug, Default, Deserialize)]
358#[serde(deny_unknown_fields)]
359struct RawWebSection {
360 root: Option<String>,
361 index: Option<String>,
362 extension: Option<RawWebExtensionSection>,
363}
364
365impl NvManifest {
366 pub fn parse_toml(src: &str) -> Result<Self, ManifestError> {
368 let raw: RawNvManifest =
369 toml::from_str(src).map_err(|e| ManifestError::TomlParse(e.to_string()))?;
370
371 let presence = match raw.app.presence.as_deref() {
372 Some(s) => AppPresenceConfig::parse(s)?,
373 None => AppPresenceConfig::Standard,
374 };
375 let name = raw.app.name.as_deref().map(|v| validate_non_empty_label("app.name", v)).transpose()?;
376 let id = raw.app.id.as_deref().map(|v| validate_app_id("app.id", v)).transpose()?;
377 let executable = raw
378 .app
379 .executable
380 .as_deref()
381 .map(|v| validate_single_filename("app.executable", v))
382 .transpose()?;
383 if let Some(0) = raw.app.width {
384 return Err(ManifestError::InvalidField { field: "app.width", reason: "must be >= 1".to_owned() });
385 }
386 if let Some(0) = raw.app.height {
387 return Err(ManifestError::InvalidField { field: "app.height", reason: "must be >= 1".to_owned() });
388 }
389 let shell = AppShellSection {
390 macos: validate_shell_choice("app.shell.macos", raw.app.shell.macos, &["macos", "skia"])?,
391 linux: validate_shell_choice("app.shell.linux", raw.app.shell.linux, &["gtk", "qt", "skia"])?,
392 windows: validate_shell_choice("app.shell.windows", raw.app.shell.windows, &["windows", "skia"])?,
393 android: raw.app.shell.android.as_deref().map(AndroidShell::parse).transpose()?,
394 };
395
396 let mut url_schemes = Vec::with_capacity(raw.apple.url_schemes.len());
397 for s in raw.apple.url_schemes {
398 url_schemes.push(validate_non_empty_label("apple.url_schemes", &s)?);
399 }
400 let mut usage_descriptions = BTreeMap::new();
401 for (k, v) in raw.apple.usage_descriptions {
402 usage_descriptions.insert(
403 validate_non_empty_label("apple.usage_descriptions", &k)?,
404 validate_non_empty_label("apple.usage_descriptions", &v)?,
405 );
406 }
407 let mut entitlements = BTreeMap::new();
408 for (k, v) in raw.apple.entitlements {
409 let key = validate_non_empty_label("apple.entitlements", &k)?;
410 let validated_val = match v {
411 EntitlementValue::Bool(b) => EntitlementValue::Bool(b),
412 EntitlementValue::String(s) => {
413 EntitlementValue::String(validate_non_empty_label("apple.entitlements", &s)?)
414 }
415 EntitlementValue::Array(items) => {
416 let mut clean = Vec::with_capacity(items.len());
417 for item in items {
418 clean.push(validate_non_empty_label("apple.entitlements", &item)?);
419 }
420 EntitlementValue::Array(clean)
421 }
422 };
423 entitlements.insert(key, validated_val);
424 }
425 let apple = AppleSection {
426 min_macos: match raw.apple.min_macos.as_deref() {
427 Some(v) => emit::validate_apple_version("apple.min_macos", v)?,
428 None => "13.0".to_owned(),
429 },
430 min_ios: match raw.apple.min_ios.as_deref() {
431 Some(v) => emit::validate_apple_version("apple.min_ios", v)?,
432 None => "17.0".to_owned(),
433 },
434 min_ios_explicit: raw.apple.min_ios.is_some(),
435 url_schemes,
436 usage_descriptions,
437 entitlements,
438 };
439
440 let mut permissions = Vec::with_capacity(raw.android.permissions.len());
441 for p in raw.android.permissions {
442 permissions.push(validate_non_empty_label("android.permissions", &p)?);
443 }
444 let min_sdk = raw.android.min_sdk.unwrap_or(24);
445 let target_sdk = raw.android.target_sdk.unwrap_or(35);
446 if min_sdk == 0 || target_sdk == 0 || min_sdk > target_sdk {
447 return Err(ManifestError::InvalidField {
448 field: "android.min_sdk",
449 reason: format!("must satisfy 1 <= min_sdk ({min_sdk}) <= target_sdk ({target_sdk})"),
450 });
451 }
452 let android = AndroidSection { min_sdk, target_sdk, permissions };
453
454 let web_root = match raw.web.root.as_deref() {
455 Some(v) => validate_rel_path_inner("web.root", v, true)?,
456 None => "web".to_owned(),
457 };
458 let web_index = match raw.web.index.as_deref() {
459 Some(v) => validate_rel_asset_path("web.index", v)?,
460 None => "index.html".to_owned(),
461 };
462 let extension = match raw.web.extension {
463 Some(ext) => {
464 let ext_name = ext
465 .name
466 .as_deref()
467 .map(|v| validate_non_empty_label("web.extension.name", v))
468 .transpose()?;
469 let popup = match ext.popup.as_deref() {
470 Some(v) => validate_rel_asset_path("web.extension.popup", v)?,
471 None => "popup.html".to_owned(),
472 };
473 let service_worker = match ext.service_worker.as_deref() {
474 Some(v) => validate_rel_asset_path("web.extension.service_worker", v)?,
475 None => "background.js".to_owned(),
476 };
477 let mut assets = Vec::with_capacity(ext.assets.len());
478 for a in ext.assets {
479 assets.push(validate_rel_asset_path("web.extension.assets", &a)?);
480 }
481 Some(WebExtensionSection { name: ext_name, popup, service_worker, assets })
482 }
483 None => None,
484 };
485
486 let export_section = export::parse_export_section(raw.export)?;
487 let docs_section = docs::parse_docs_section(raw.docs)?;
488
489 Ok(Self {
490 app: AppSection {
491 name,
492 id,
493 executable,
494 presence,
495 width: raw.app.width,
496 height: raw.app.height,
497 multi_scene: raw.app.multi_scene,
498 pip: raw.app.pip,
499 shell,
500 },
501 apple,
502 android,
503 web: WebSection { root: web_root, index: web_index, extension },
504 export: export_section,
505 docs: docs_section,
506 })
507 }
508
509 pub fn load_file(path: &Path) -> Result<Self, ManifestError> {
511 let raw = fs::read_to_string(path)
512 .map_err(|e| ManifestError::Io(format!("{}: {e}", path.display())))?;
513 Self::parse_toml(&raw)
514 }
515
516 pub fn load_for_dir(manifest_dir: &Path) -> Result<Self, ManifestError> {
518 let path = manifest_dir.join("nativeview.toml");
519 if path.is_file() { Self::load_file(&path) } else { Ok(Self::default()) }
520 }
521
522 #[must_use]
524 pub fn resolved_name(&self, info: &ManifestAppInfo) -> String {
525 self.app.name.clone().unwrap_or_else(|| info.package_name.clone())
526 }
527
528 #[must_use]
530 pub fn resolved_id(&self, info: &ManifestAppInfo) -> String {
531 if let Some(id) = &self.app.id {
532 return id.clone();
533 }
534 let sanitized: String = info
535 .lib_name
536 .chars()
537 .map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '.' })
538 .collect();
539 let compact: String = sanitized
540 .split('.')
541 .filter(|s| !s.is_empty())
542 .collect::<Vec<_>>()
543 .join(".");
544 format!("io.github.nativeview.{}", if compact.is_empty() { "app" } else { &compact })
545 }
546
547 #[must_use]
549 pub fn resolved_executable(&self, info: &ManifestAppInfo) -> String {
550 if let Some(exe) = &self.app.executable {
551 return exe.clone();
552 }
553 if let Some(name) = &self.app.name {
554 let pascal = to_pascal_case(name);
555 if !pascal.is_empty() {
556 return pascal;
557 }
558 }
559 info.lib_name.clone()
560 }
561
562 #[must_use]
565 pub fn requires_macos_app_bundle(&self) -> bool {
566 !self.apple.usage_descriptions.is_empty()
567 || !self.apple.entitlements.is_empty()
568 || self.app.presence != AppPresenceConfig::Standard
569 }
570
571 #[must_use]
573 pub fn emit_macos_info_plist(&self, info: &ManifestAppInfo, bundle_id_override: Option<&str>) -> String {
574 emit::emit_macos_info_plist(self, info, bundle_id_override)
575 }
576
577 #[must_use]
579 pub fn emit_ios_info_plist(&self, info: &ManifestAppInfo) -> String {
580 emit::emit_ios_info_plist(self, info, false)
581 }
582
583 #[must_use]
585 pub fn emit_ios_sim_info_plist(&self, info: &ManifestAppInfo) -> String {
586 emit::emit_ios_info_plist(self, info, true)
587 }
588
589 #[must_use]
591 pub fn emit_apple_entitlements_plist(&self) -> Option<String> {
592 emit::emit_apple_entitlements_plist(self, false)
593 }
594
595 #[must_use]
597 pub fn emit_ios_entitlements_plist(&self) -> Option<String> {
598 emit::emit_apple_entitlements_plist(self, true)
599 }
600
601 pub fn resolved_android_id(&self, info: &ManifestAppInfo) -> Result<String, ManifestError> {
606 if let Some(explicit) = &self.app.id {
607 return validate_android_package_id(explicit);
608 }
609 let fallback = sanitize_android_package_id(&self.resolved_id(info));
610 validate_android_package_id(&fallback)
611 }
612
613 #[must_use]
615 pub fn emit_android_manifest_xml(&self, info: &ManifestAppInfo) -> String {
616 emit::emit_android_manifest_xml(self, info, AndroidShell::Compose)
617 }
618
619 #[must_use]
621 pub fn emit_android_manifest_xml_for(&self, info: &ManifestAppInfo, shell: AndroidShell) -> String {
622 emit::emit_android_manifest_xml(self, info, shell)
623 }
624
625 pub fn emit_web_mv3_manifest_json(&self, info: &ManifestAppInfo) -> Result<String, ManifestError> {
627 emit::emit_web_mv3_manifest_json(self, info)
628 }
629}