nativeview-codegen 0.1.0-rc.1

Multi-language ABI, policy, flat-op codec, and hybrid Direct-FFI code generator for Native View Engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! Shared Intermediate Representation (IR) for bi-directional React Native <-> NV codegen.

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::error::CodegenError;

/// Typed value representation shared by RN Fabric props, event payloads, commands, and TurboModules.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PropType {
    Bool,
    Int32,
    Float,
    Double,
    String,
    Color,
    ImageSource,
    Point,
    EdgeInsets,
    Dimension,
    StringEnum { variants: Vec<String> },
    IntEnum { variants: Vec<i32> },
    Array { item: Box<PropType> },
    Object { fields: Vec<ObjectField> },
    Mixed,
    Void,
    Promise { inner: Box<PropType> },
    Callback { params: Vec<ParamSpec> },
}

/// Named field inside a structured object prop or event payload.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ObjectField {
    pub name: String,
    pub field_type: PropType,
    #[serde(default)]
    pub optional: bool,
    #[serde(default)]
    pub nullable: bool,
}

/// Typed literal default value extracted from `WithDefault<T, default>`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
pub enum DefaultValue {
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    String(String),
}

/// Component prop specification.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PropSpec {
    pub name: String,
    pub prop_type: PropType,
    #[serde(default)]
    pub optional: bool,
    #[serde(default)]
    pub nullable: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_value: Option<DefaultValue>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub doc: Option<String>,
}

/// React Native Fabric event dispatch semantics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum EventBubbling {
    #[default]
    Direct,
    Bubbling,
}

/// Component event handler specification (`DirectEventHandler` / `BubblingEventHandler`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EventSpec {
    pub name: String,
    #[serde(default)]
    pub bubbling: EventBubbling,
    #[serde(default = "default_true")]
    pub optional: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub paper_top_level_name: Option<String>,
    #[serde(default)]
    pub payload: Vec<ObjectField>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payload_type_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub doc: Option<String>,
}

fn default_true() -> bool {
    true
}

/// Parameter for a native command or TurboModule method.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ParamSpec {
    pub name: String,
    pub param_type: PropType,
    #[serde(default)]
    pub optional: bool,
}

/// Imperative native command declared via `codegenNativeCommands`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CommandSpec {
    pub name: String,
    #[serde(default)]
    pub params: Vec<ParamSpec>,
}

/// Optional second-argument metadata passed to `codegenNativeComponent(name, options)`.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ComponentOptions {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub paper_component_name: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub excluded_platforms: Vec<String>,
    #[serde(default)]
    pub interface_only: bool,
}

/// Parsed React Native Fabric `*NativeComponent.{ts,js}` specification.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RnComponentSpec {
    pub component_name: String,
    pub props_type_name: String,
    pub extends_view_props: bool,
    pub props: Vec<PropSpec>,
    pub events: Vec<EventSpec>,
    pub commands: Vec<CommandSpec>,
    pub options: ComponentOptions,
}

/// Parsed method on a React Native `TurboModule` `Spec` interface.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TurboModuleMethod {
    pub name: String,
    pub params: Vec<ParamSpec>,
    pub return_type: PropType,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub doc: Option<String>,
}

/// Parsed React Native `Native*.{ts,js}` TurboModule specification.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TurboModuleSpec {
    pub module_name: String,
    pub enforcing: bool,
    pub methods: Vec<TurboModuleMethod>,
}

/// Result of parsing any React Native Codegen spec file.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "spec_kind", rename_all = "snake_case")]
pub enum ParsedRnSpec {
    Component(RnComponentSpec),
    TurboModule(TurboModuleSpec),
}

impl ParsedRnSpec {
    pub fn name(&self) -> &str {
        match self {
            Self::Component(c) => &c.component_name,
            Self::TurboModule(m) => &m.module_name,
        }
    }
}


/// A single generated artifact with its relative output path and full UTF-8 source.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GeneratedFile {
    pub relative_path: String,
    pub content: String,
}

/// Output bundle for Direction 1 (`import_rn`: RN -> NV).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ImportRnOutput {
    pub spec: ParsedRnSpec,
    pub rust_module: GeneratedFile,
    /// C++20 host interface a native host implements (TurboModules only; components are Rust-only).
    pub cpp_turbomodule_host: Option<GeneratedFile>,
}

impl ImportRnOutput {
    pub fn files(&self) -> Vec<&GeneratedFile> {
        std::iter::once(&self.rust_module)
            .chain(self.cpp_turbomodule_host.as_ref())
            .collect()
    }

    pub fn write_to_dir(&self, out_dir: &Path) -> Result<Vec<PathBuf>, CodegenError> {
        write_generated_files(out_dir, &self.files())
    }
}

/// Target framework for multi-target export from `#[nativeview_hybrid_spec]` / `#[nv_hybrid_view]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ExportTarget {
    ReactNative,
    NitroUi,
    Flutter,
    SwiftUi,
    Compose,
    WebComponent,
}

impl ExportTarget {
    pub const ALL: &'static [ExportTarget] = &[
        ExportTarget::ReactNative,
        ExportTarget::NitroUi,
        ExportTarget::Flutter,
        ExportTarget::SwiftUi,
        ExportTarget::Compose,
        ExportTarget::WebComponent,
    ];

    pub fn dir_name(self) -> &'static str {
        match self {
            Self::ReactNative => "react-native",
            Self::NitroUi => "nitro-ui",
            Self::Flutter => "flutter",
            Self::SwiftUi => "swiftui",
            Self::Compose => "compose",
            Self::WebComponent => "web-component",
        }
    }

    pub fn from_name(raw: &str) -> Result<Self, CodegenError> {
        let s = raw.trim();
        if s.eq_ignore_ascii_case("rn")
            || s.eq_ignore_ascii_case("react-native")
            || s.eq_ignore_ascii_case("react_native")
            || s.eq_ignore_ascii_case("fabric")
        {
            Ok(Self::ReactNative)
        } else if s.eq_ignore_ascii_case("nitro-ui")
            || s.eq_ignore_ascii_case("nitro_ui")
            || s.eq_ignore_ascii_case("nitroui")
            || s.eq_ignore_ascii_case("nitro")
        {
            Ok(Self::NitroUi)
        } else if s.eq_ignore_ascii_case("flutter") || s.eq_ignore_ascii_case("dart") {
            Ok(Self::Flutter)
        } else if s.eq_ignore_ascii_case("swiftui")
            || s.eq_ignore_ascii_case("swift-ui")
            || s.eq_ignore_ascii_case("swift")
            || s.eq_ignore_ascii_case("ios")
        {
            Ok(Self::SwiftUi)
        } else if s.eq_ignore_ascii_case("compose")
            || s.eq_ignore_ascii_case("jetpack-compose")
            || s.eq_ignore_ascii_case("kotlin")
            || s.eq_ignore_ascii_case("android")
        {
            Ok(Self::Compose)
        } else if s.eq_ignore_ascii_case("web")
            || s.eq_ignore_ascii_case("web-component")
            || s.eq_ignore_ascii_case("web_component")
            || s.eq_ignore_ascii_case("wasm")
            || s.eq_ignore_ascii_case("custom-element")
        {
            Ok(Self::WebComponent)
        } else {
            Err(CodegenError::validation(format!(
                "unknown export target '{s}'; expected one of: rn, nitro-ui, web, swiftui, compose, flutter"
            )))
        }
    }
}

/// Output bundle for `export_rn` (NV -> React Native Fabric NativeComponent).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExportRnOutput {
    pub view_name: String,
    pub native_component_ts: GeneratedFile,
    pub ios_component_view_mm: GeneratedFile,
    pub android_view_manager_kt: GeneratedFile,
    pub android_react_package_kt: GeneratedFile,
    pub windows_component_view_hpp: GeneratedFile,
}

impl ExportRnOutput {
    pub fn files(&self) -> [&GeneratedFile; 5] {
        [
            &self.native_component_ts,
            &self.ios_component_view_mm,
            &self.android_view_manager_kt,
            &self.android_react_package_kt,
            &self.windows_component_view_hpp,
        ]
    }

    pub fn write_to_dir(&self, out_dir: &Path) -> Result<Vec<PathBuf>, CodegenError> {
        write_generated_files(out_dir, &self.files())
    }
}

/// Output bundle for `export_nitro_ui` (`margelo/nitro-ui` bare Nitro view module).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExportNitroUiOutput {
    pub view_name: String,
    pub nitro_spec_ts: GeneratedFile,
    pub view_ts: GeneratedFile,
    pub ios_hybrid_swift: GeneratedFile,
    pub android_hybrid_kt: GeneratedFile,
    pub nitro_json: GeneratedFile,
}

impl ExportNitroUiOutput {
    pub fn files(&self) -> [&GeneratedFile; 5] {
        [
            &self.nitro_spec_ts,
            &self.view_ts,
            &self.ios_hybrid_swift,
            &self.android_hybrid_kt,
            &self.nitro_json,
        ]
    }

    pub fn write_to_dir(&self, out_dir: &Path) -> Result<Vec<PathBuf>, CodegenError> {
        write_generated_files(out_dir, &self.files())
    }
}

/// Output bundle for `export_flutter`: typed Dart `StatefulWidget` using `dart:ffi`
/// + `package:nativeview_flutter/nativeview_flutter.dart`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExportFlutterOutput {
    pub view_name: String,
    pub dart_widget: GeneratedFile,
}

impl ExportFlutterOutput {
    pub fn files(&self) -> [&GeneratedFile; 1] {
        [&self.dart_widget]
    }

    pub fn write_to_dir(&self, out_dir: &Path) -> Result<Vec<PathBuf>, CodegenError> {
        write_generated_files(out_dir, &self.files())
    }
}

/// Output bundle for `export_swiftui`: typed SwiftUI `View` wrapping `NativeViewSwiftUI.NvSurfaceRepresentable`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExportSwiftUiOutput {
    pub view_name: String,
    pub swift_view: GeneratedFile,
}

impl ExportSwiftUiOutput {
    pub fn files(&self) -> [&GeneratedFile; 1] {
        [&self.swift_view]
    }

    pub fn write_to_dir(&self, out_dir: &Path) -> Result<Vec<PathBuf>, CodegenError> {
        write_generated_files(out_dir, &self.files())
    }
}

/// Output bundle for `export_compose`: typed Kotlin `@Composable` wrapping `io.github.nativeview.compose.NvSurface`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExportComposeOutput {
    pub view_name: String,
    pub compose_kt: GeneratedFile,
}

impl ExportComposeOutput {
    pub fn files(&self) -> [&GeneratedFile; 1] {
        [&self.compose_kt]
    }

    pub fn write_to_dir(&self, out_dir: &Path) -> Result<Vec<PathBuf>, CodegenError> {
        write_generated_files(out_dir, &self.files())
    }
}

/// Output bundle for `export_web_component`: Light-DOM Custom Element `<nv-...>` + `.d.ts` + typed React `.tsx`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExportWebComponentOutput {
    pub view_name: String,
    pub tag_name: String,
    pub element_js: GeneratedFile,
    pub types_dts: GeneratedFile,
    pub react_tsx: GeneratedFile,
}

impl ExportWebComponentOutput {
    pub fn files(&self) -> [&GeneratedFile; 3] {
        [&self.element_js, &self.types_dts, &self.react_tsx]
    }

    pub fn write_to_dir(&self, out_dir: &Path) -> Result<Vec<PathBuf>, CodegenError> {
        write_generated_files(out_dir, &self.files())
    }
}

/// Unified multi-target export bundle returned by [`crate::export_target`] / [`crate::export_all_targets`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MultiTargetExportOutput {
    pub target: ExportTarget,
    pub files: Vec<GeneratedFile>,
}

impl MultiTargetExportOutput {
    pub fn write_to_dir(&self, out_dir: &Path) -> Result<Vec<PathBuf>, CodegenError> {
        let refs: Vec<&GeneratedFile> = self.files.iter().collect();
        write_generated_files(out_dir, &refs)
    }
}

pub(crate) fn write_generated_files(
    out_dir: &Path,
    files: &[&GeneratedFile],
) -> Result<Vec<PathBuf>, CodegenError> {
    let mut written = Vec::with_capacity(files.len());
    for file in files {
        let dest = out_dir.join(&file.relative_path);
        if let Some(parent) = dest.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| CodegenError::io(parent.display().to_string(), e))?;
        }
        std::fs::write(&dest, &file.content)
            .map_err(|e| CodegenError::io(dest.display().to_string(), e))?;
        written.push(dest);
    }
    Ok(written)
}